如何dequeueReusableCellWithIdentifier:对待不同的indexPath?

让我们看看一些标准的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如何知道不同的行?

如果我们在数组中有10个项目,那么它将为每个indexPath.row分配10个单元格

这是不正确的 – 通常分配的单元格数将是NumberOfVisibleRows + 2(或类似的值)。

这大致上是UITableView的工作原理:一旦某个单元格从可见区域滚出,它将从UITableView视图层次结构中移除(将表格的clipToBounds属性设置为NO,您将可以看到!),并将其放入某种的内部caching。 dequeueReusableCellWithIdentifier:方法检查是否有单元可用于该caching中的重用并返回(如果没有单元格可用,则返回nil) – 因此您不需要分配更多的单元格,然后实际适合可见区域。

dequeueReusableCellWithIdentifier方法不依赖于当前的indexPath,而是依赖于传递给它的单元格string标识符。 indexPath只用于获取适当的内容给单元格。

呵呵,方法**dequeueReusableCellWithIdentifier**:与indexPath无关。

当使用UITableView时,我们使用[[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault] reuseIdentifier:cellIdentifier]将一个非常亲切的单元格放入caching中(也许是一个NSMutableDictionary),并使用键“cellIdentifier”。 然后,当我们需要更多的单元格时,我们首先查询caching,如果错过了,我们创build一个新的caching。

indexPath是编码人员的责任。 您可以按区域分隔不同types的单元格,并在一个区域中逐行显示单元格。 部分和行组成了一个NSIndexPath