故事板中tableviewController中的原型tableview单元格

时间:2014-08-22 23:54:03

标签: ios uitableview storyboard

我有一个原本不是故事板应用程序的应用程序。我之后添加了一个功能分支的故事板,并且有一个UITableViewController的子类。我创建了一个包含多个UILabelsUIImageViews的原型单元格,并为每个单元格添加了标签。原型单元格具有正确的标识符。

我已使用标识符注册了该课程:

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CustomCell"];

当我尝试将自定义单元格出列并访问其视图时:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];
UIImageView *icon = (UIImageView *)[cell viewWithTag:1];

视图(图标)为零。

我还尝试了对其进行子类化,并使用重用标识符注册子类,并在原型中将UITableViewCell与子类名称一起设置。在那种情况下,

UIImageView *icon = cell.icon; 

仍然会返回nil。

故事板与主要故事板有关吗?我还有其他项目,其中自定义subviews的原型单元正常工作,没有这些麻烦。有没有办法注册自定义类或UITableViewCell自定义标识符,但指定它来自哪个故事板?

1 个答案:

答案 0 :(得分:5)

好的,我已经弄明白了,而且我要回答是为了记下我学到的一些小事。

我的控制器正在使用alloc / init而不是

进行实例化
[_storyboard instantiateViewControllerWithIdentifier:@".."]. 

这意味着故事板从未使用过,原型单元格从未注册过。

因此,当使用辅助故事板并且以编程方式而不是通过segue实例化控制器时,请确保使用instantiateViewControllerWithIdentifier。

不要注册单元格或注册自定义类:

// don't do this
[self.tableView registerClass:[ClaimsCell class] forCellReuseIdentifier:@"ClaimsCell"];

使用以下方法将单元格取消:

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddClaimCell" forIndexPath:indexPath];

这样,编译器实际上会通知您原型单元尚未连接。不要试图使用旧的tableview dequeue调用:

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddClaimCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CustomCell"];
    }

因为如果您正确地连接了故事板,那么单元格将始终由forIndexPath:call返回。

我选择将UITableViewCell与视图标记一起使用,而不是使用自定义类。但是原型单元可以设置为自定义UITableViewCell子类,如果它们已连接到故事板中,则可以引用各个单元格元素。

实例化UITableViewCell:

    UIImageView *icon = (UIImageView *)[cell viewWithTag:1];
    UILabel *labelDescription = (UILabel *)[cell viewWithTag:2];
    UILabel *labelStatus = (UILabel *)[cell viewWithTag:3];

实例化CustomCell:

    UIImageView *icon = cell.iconStatus;
    UILabel *labelDescription = cell.labelDescription;
    UILabel *labelStatus = cell.labelStatus;