UITableView单元在初始化时不是零

And*_*nov 4 uitableview ios ios5 uistoryboard xcode-storyboard

我正在设置我的UITableView故事板编辑器.为了创建我的单元格,我使用标准委托方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCell"];
        if (cell == nil)
        {
        // Do cell setup
        }
    // etc
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

除非细胞第一次出现,否则它应该是非零的.所以if语句中的代码永远不会被执行.

当人们的重用标识符不一致时,人们会收到此错误,因此我继续验证我在故事板视图中使用与我的代码中完全相同的重用标识符.仍然面临着这个问题.我在项目中也有几个表视图,每个都有一个唯一的重用标识符.仍然没有骰子.任何人都知道其他任何错误吗?

Ste*_*her 12

这不是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;
}
Run Code Online (Sandbox Code Playgroud)

在使用重用标识符创建单元格时,只需在此处进行初始设置.没有特定于此特定行/ indexPath的内容.

在我放置每行设置注释的地方,你有一个正确标识符的单元格.它可以是新鲜细胞,也可以是再生细胞.您负责与此特定行/ indexPath相关的所有设置.

示例:如果您在某些行(可能)中设置文本,则需要在所有行中设置或清除它,或者您设置的行中的文本将泄漏到您不设置的单元格中.

使用故事板原型

但是,通过故事板,故事板和表格视图可以处理最初的单元格创建!这是很棒的东西.在使用故事板时,您可以直接在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;
}
Run Code Online (Sandbox Code Playgroud)

您负责与以前相同的每行设置,但您不需要编写代码来构建初始的空单元格,无论是内联还是自己的子类.

正如Ian在下面所说,您仍然可以使用旧方法.只需确保不在故事板中包含指定标识符的单元格原型.视图控制器将无法从单元原型构建您的单元格,dequeueReusableCellWithIdentifier将返回nil,并且您将完全处于以前的位置.