让我们看一些tableview的标准代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
static int count = 0;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
NSLog(@"count %d", count++);
}
// Configure the cell...
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
如果数组中有 10 个项目,那么它将为每个 indexPath.row 分配 10 个单元格
我的问题是 函数 reuseIdentifier:CellIdentifier 如何知道不同的行?
最佳答案
If we have 10 items in array, then it will alloc 10 cells for each indexPath.row
这不是真的 - 通常分配的单元格数将是 NumberOfVisibleRows+2(或类似的值)。
这(大致)是 UITableView 的工作原理:一旦某个单元格滚动出可见区域,它就会从 UITableView View 层次结构中删除(将表的 clipToBounds 属性设置为 NO,您将能够看到它!)并放入某种内部缓存。 dequeueReusableCellWithIdentifier:
方法检查该缓存中是否有可重用的单元格并返回它(如果没有单元格可用则返回 nil)- 因此您不需要分配比实际适合可见区域更多的单元格。
dequeueReusableCellWithIdentifier
方法不依赖于当前的 indexPath,而是依赖于您传递给它的单元格字符串标识符。 indexPath 仅供您用于获取单元格的适当内容。
关于objective-c - 如何 dequeueReusableCellWithIdentifier : treat different indexPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5947186/