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

mit*_*ade 1 storyboard uitableview ios

我有一个原本不是故事板应用程序的应用程序.我已经为一个功能分支添加了一个故事板,并且它上面有一个子类UITableViewController.我创建了一个原型细胞与几个UILabelsUIImageViews,并添加标签为他们每个人.原型单元具有正确的标识符.

我已经使用标识符注册了类:

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CustomCell"];
Run Code Online (Sandbox Code Playgroud)

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

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

视图(图标)为零.

我也尝试了对它进行子类化,并使用重用标识符注册子类,并UITableViewCell在原型中设置子类名称.在这种情况下,

UIImageView *icon = cell.icon; 
Run Code Online (Sandbox Code Playgroud)

仍然返回零.

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

mit*_*ade 5

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

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

[_storyboard instantiateViewControllerWithIdentifier:@".."]. 
Run Code Online (Sandbox Code Playgroud)

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

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

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

// don't do this
[self.tableView registerClass:[ClaimsCell class] forCellReuseIdentifier:@"ClaimsCell"];
Run Code Online (Sandbox Code Playgroud)

使用以下方法将单元格出列

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddClaimCell" forIndexPath:indexPath];
Run Code Online (Sandbox Code Playgroud)

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

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

因为如果你已经连接了故事板,那么单元格将始终由forIndexPath:call返回.

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

实例化UITableViewCell:

    UIImageView *icon = (UIImageView *)[cell viewWithTag:1];
    UILabel *labelDescription = (UILabel *)[cell viewWithTag:2];
    UILabel *labelStatus = (UILabel *)[cell viewWithTag:3];
Run Code Online (Sandbox Code Playgroud)

实例化CustomCell:

    UIImageView *icon = cell.iconStatus;
    UILabel *labelDescription = cell.labelDescription;
    UILabel *labelStatus = cell.labelStatus;
Run Code Online (Sandbox Code Playgroud)

  • 我建议你停止使用viewWithTag,而是使用UITableViewCell的自定义类,你可以使用正确的插座.Specialized View子类是实现Model,View和Controller之间分离的一个非常重要的部分. (3认同)