我知道这里有很多与此主题相关的问题,但我找不到与我的问题相匹配的问题。我有一个名为“CustomTableViewCell”的 UITableViewCell
子类。
但是下面提到的代码工作正常,我的单元格中有复选标记,我想停止可重用性,因为单元格的最大数量不会超过 25,因此它不会影响性能,我想经过多次搜索,我发现我必须删除 tableView dequeueReusableCellWithIdentifier
方法或者只是将标识符更改为 nil,但不幸的是,当我这样做时我得到空单元格,我的应用程序崩溃了我在这里错过了什么?
这很好用,但它重用了单元格。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomCell";
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
...
...
...
...
return cell;
}
相反,这段代码崩溃了:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomCell";
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
...
...
return cell;
}
最佳答案
实现 prepareForReuse
我强烈建议您使用重用模式,在我看来,不这样做是不好的做法。我想您避免使用重用模式的真正原因是您在重用自定义单元格时会看到“旧”状态。
为避免这种情况,您应该在自定义单元格中实现/覆盖 prepareForReuse 方法,在此方法中,您可以将所有自定义属性设置为其默认状态。
在 cellForRowAtIndexPath 中,您只需重复使用单元格并将自定义属性设置为其值。
- (void)prepareForReuse() {
[super prepareForReuse];
//Set your custom properties to their default state
self.custom1 = ...;
self.custom2 = ...;
}
关于iphone - 停止 UITableViewCell 的可重用性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16534360/