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

问题描述 投票:1回答:1

我有一个原本不是故事板应用程序的应用程序。我已经添加了一个功能分支的故事板,并且有一个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; 

仍然返回零。

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

ios uitableview storyboard
1个回答
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;
© www.soinside.com 2019 - 2024. All rights reserved.