这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifierNormal = @"CellNormal";
static NSString *CellIdentifierTracking = @"CellTracking";
switch (self.mapState) {
case MapStateNormal:
{
// UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:CellIdentifierNormal];
// if (cell == nil) {
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierNormal];
// }
[cell.textLabel setText:@"abc"];
return cell;
}
case MapStateTracking:
{
// UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:CellIdentifierTracking];
// if (cell == nil) {
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierTracking];
// }
if (indexPath.row == 0) {
[cell.textLabel setText:@"Lorem ipsum"];
} else {
NSURL *url = [LoremIpsum URLForPlaceholderImageFromService:LoremIpsumPlaceholderImageServicePlaceKittenCom
withWidth:1024
height:1024];
[cell.imageView setImageWithURL:url
placeholderImage:[UIImage imageNamed:@"MenuButton"]];
}
return cell;
}
default:
break;
}
return nil;
}
这段代码工作正常但不是最佳实践,因为我每次都重新创建 UITableViewCell
。它显示如下:
但是,当我取消注释上面的那些行以启用 dequeueReusableCell
时,表格会显示其单元格,其中包含如下错误(黄色部分是我的代码):
您可以看到第一行有一个 UIImage
,下面几行有文本,而我显然没有在我的代码中设置它。
我该怎么做才能解决这个问题?还是我应该坚持使用第一种方法?
谢谢。
最佳答案
你真的应该重新使用表格 View 单元格,因为如果你一直重新创建它们会带来很多开销,即注释掉的代码是正确的。
接下来,docs说:“tableView:cellForRowAtIndexPath:
中的 TableView 委托(delegate)在重用单元格时应始终重置所有内容。”
如果您不重置内容,它将再次显示。
所以我建议你设置
cell.imageView.image = nil;
在你的 -(UITableViewCell *)tableView:cellForRowAtIndexPath:(NSIndexPath *)indexPath
方法中。
关于ios - UITableViewCell 在滚动时显示错误的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23774179/