这不再是 UITableView 的工作方式了。阅读您的问题,我认为您可能对它之前的工作方式也感到困惑。如果没有,抱歉,本文的第一部分只是回顾。:)
没有故事板单元原型
以下是它过去的工作方式:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// If the tableview has an offscreen, unused cell of the right identifier
// it will return it.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCell"];
if (cell == nil)
{
// Initial creation, nothing row specific.
}
// Per row setup here.
return cell;
}
在这里,当您使用重用标识符创建单元时,您只需在此处进行初始设置。没有特定于这个特定的行/索引路径。
在我放置每行设置注释的地方,你有一个正确标识符的单元格。它可能是新鲜的电池,也可能是回收的电池。您负责与此特定行/索引路径相关的所有设置。
示例:如果您在某些行中设置文本(可能),您需要在所有行中设置或清除它,或者您设置的行中的文本将泄漏到您没有设置的单元格中。
使用故事板原型
但是,使用故事板,故事板和表格视图会处理初始单元格的创建!这是很棒的东西。使用情节提要时,您可以直接在 tableview 中绘制单元原型,Cocoa Touch 将为您完成初始创建。
相反,你会得到这个:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCell"];
// You'll always have a cell now!
// Per row setup here.
return cell;
}
您负责与以前一样的每行设置,但您不需要编写代码来构建初始空单元格,无论是内联还是在其自己的子类中。
正如 Ian 在下面指出的,您仍然可以使用旧方法。只需确保不要在情节提要中为您指定的标识符包含单元原型。视图控制器将无法从单元原型构建您的单元,dequeueReusableCellWithIdentifier
将返回 nil,并且您将完全回到以前的位置。