我使用TableView与TableViewCell。我以编程方式添加了一个ImageView, Text和一个uibutton到单元格。按钮的框架在纵向和横向方向上设置不同。但是当设备从纵向旋转到横向时,显示的是两个按钮而不是一个。
我试着在横向模式下删除按钮,按钮不起作用。
switch ([indexPath section])
{
case 0:
{
cell.imageView.image = [UIImage imageNamed:@"active.png"];
cell.textLabel.text = @"Application Name";
self.uninstallApplicationButton = [[UIButton alloc] init];
self.uninstallApplicationButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.uninstallApplicationButton setTitle:@"Install" forState: UIControlStateNormal];
[self.uninstallApplicationButton setBackgroundColor:[UIColor brownColor]];
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (device == UIUserInterfaceIdiomPhone)
{
if (UIInterfaceOrientationIsLandscape(orientation))
{
self.uninstallApplicationButton.frame = CGRectMake(490.0, 25.0, 65.0, 30.0);
}
else if(UIInterfaceOrientationIsPortrait(orientation))
{
self.uninstallApplicationButton.frame = CGRectMake(250.0, 25.0, 65.0, 30.0);
}
}
else if(device == UIUserInterfaceIdiomPad)
{
self.uninstallApplicationButton.frame = CGRectMake(600.0, 25.0, 150.0, 30.0);
}
}
[cell.contentView addSubview:uninstallApplicationButton];
break;
您说代码在您的-cellForRow(at:)
方法中。由于表视图重用它们的单元格,您的代码必须考虑它所配置的单元格可能已经在以前配置过了。一个好的方法是避免在此方法中向单元格添加任何按钮或其他视图,而只是在故事板中添加它们。如果您必须在单元格中添加视图,您应该删除之前添加的视图,或者只是重用它们,避免再次添加它们。
你需要在alloc init之前将button从父视图中移除