这是人们在重复使用表格单元格时遇到的常见问题。
该行尝试重用单元格。这意味着如果单元格 0 移出屏幕,它将被重新用作单元格 5:
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
如果某个单元格无法重复使用,您将创建一个新单元格:
if (cell == nil){
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
下一行是您的问题,仅当单元格无法重复使用时才设置单元格。发生 5 次(对于表格可见时可见的单元格)。
但是您的表格随后想要显示的所有单元格都将被重复使用已经包含内容的单元格。
// Set up the cell
/*...*/
但别担心。这很容易解决。您必须将单元的创建与其配置分开。只需像这样移动一些代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil){
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
// whatever happened before. You have a valid cell at this point.
// Set up the cell
int storyIndex = indexPath.row;
//[cell setText:[[stories objectAtIndex: storyIndex] objectForKey: @"title"]];
//Story title
//cell.textLabel.text = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
//cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
cell.lTitle.text = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
cell.lSummary.text = [[stories objectAtIndex: storyIndex] objectForKey: @"summary"];
cell.lDate.text = [[stories objectAtIndex: storyIndex] objectForKey: @"date"];
return cell;
}
编辑:也许我下次应该读一下这个问题。但我想我还是100%正确的。
如果我删除 tableView:heightForRowAtIndexPath: 一切都很好(除了没有我想要的单元格大小)
我认为这是巧合。你有多少细胞?我猜大概七八点吧?一切都很好,因为您的所有细胞同时可见。所以不需要重复使用一个cell,它们都有它们应该有的内容。