IOS:停止在 UITableView 中错误地重用单元格

标签 ios uitableview uibutton switch-statement cells

我有一个包含四个部分的基本 UITableView。我用 Switch 语句控制每个部分的内容。

我以编程方式创建了一个按钮,它应该出现在前三个部分的行中,但不应出现在第四个部分中。但是,该按钮随机出现在第四部分的行中。

我认为这是因为一个单元格被重复使用,但当我使用 Switch 语句创建每个部分的行时,我看不出这是怎么发生的。任何想法表示赞赏。

我正在使用这样配置的自定义单元格:`

static NSString *CustomCellIdentifier = @"DashboardCell";

DashboardCell *cell = (DashboardCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];

if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DashboardCell"
                                                                owner:self options:nil];
    for (id oneObject in nib) if ([oneObject isKindOfClass:[DashboardCell class]])
        cell = (DashboardCell *)oneObject;
}

// Configure the cell.`

创建这个按钮的代码是:`

        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(200, 11, 50, 50);        
        UIImage *iConnect = [UIImage imageNamed:@"connect.png"];
        [button setImage:iConnect forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonSelected:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:button];`

最佳答案

您需要为每种类型的内容使用不同的重用标识符。所以这里有两种类型的内容 - 具有 UIButton 的单元格和没有的单元格。

使用tableView:cellForRowAtIndexPath: 方法的indexPath 来选择@"CellWithButton"或@"CellWithoutButton"的重用标识符。

您的代码中实际发生的是所有单元格都被赋予相同的重用标识符,这意味着它们都被放入同一个对象池中。这意味着当您使用 [tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier]; 时,您正在从这个池中检索一个单元格(它可能包含没有 UIButton 的单元格和有的单元格).因此 dequeue 方法可以随机返回一个已经添加了 UIButton 的单元格。如果您使用两个重用标识符,UITableView 将设置两个对象池,并将正确地从每个对象池中存放和检索适当的单元格。

或者您可以使用一个重用池,并在每次使用 dequeue 方法检索单元格时检查单元格中是否有 UIButton

关于IOS:停止在 UITableView 中错误地重用单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10775256/

相关文章:

ios - 如何将图像保存在 iPhone 中从 UIGraphicsGetImageFromCurrentImageContext() 捕获的系统中?

ios5 - UITableViewCell 子类中的 IFTweetLabel 未显示

indexing - 获取 UITableView 中选定附件按钮的 IndexPath

ios - 添加目标 :action:forControlEvents: unrecognized selector sent to instance - uibutton in uitablecell

swift - 首次选择 pickerView 时未触发条件

ios - 有没有办法通过 Swift 中的属性共享 getter 和 setter?

iphone - 我怎样才能用 AVPlayer 播放 pcm

ios - 不能选择 MKViewAnnotation 两次?

ios - 约束更改后 UITableView 水龙头第一次不工作

iphone - 如何调整 UIButton 的大小以适合文本而不使其比屏幕宽?