我在使用 UITableView 的新 registerClass 方法时遇到了问题。我很好地注册了我的单元格,然后当我想制作一个单元格时,我这样做:
static NSString *imageIdentifier = @"image";
CustomCell *cell = [self.tableView dequeueReusableCellWithIdentifier:imageIdentifier];
if (!cell) {
cell = [[CustomCell alloc] initWithQuestion:self.question reuseIdentifier:imageIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
这可能不是现代的方法,但这是我以前的做法。问题是,由于新的 registerClass 方法会在队列中没有单元格时为您创建一个新单元格,因此 if (!aCell) 检查失败,并且单元格未正确构建。
我没有使用这种新方法来正确取消排队吗?
1)在UITableViewCell子类的prepareForReuse
方法中设置单元格(在您的例子中为selectionStyle)。
2)在委托方法中设置dequeueReusableCellWithIdentifier:
调用后tableView:cellForRowAtIndexPath:
单元格的内容。
如果您使用相应的标识符调用了registerClass:
,dequeueReusableCellWithIdentifier:
将始终返回一个单元格。
使用新方法,dequeueReusableCellWithIdentifier:forIndexPath:
,并省略 if 子句。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];
// configure cell here
return cell;
}
注册类或 xib 时,将使用相同的重用标识符。