为什么将"viewWithTag"与"dequeueReusableCellWithIdentifier"一起使用?

cra*_*avr 12 iphone uitableview ios

谁可以解释为什么你应该使用从一个单元格viewWithTag获取子视图(例如UILabel等)dequeueReusableCellWithIdentifier

一些背景信息:我有一个UITableViewCell带有几个UILabels 的自定义(我在下面复制了一个简单的版本).这些标签在关联的NIB文件中定义,并使用IBOutlets 声明并链接回自定义单元的控制器类.在tableview中dequeueReusableCellWithIdentifier,我这样做:

CustomCell *customCell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomCellId"];
if (customCell == nil) {
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"customCell" owner:self options:nil];
    for (id oneObject in nib)
        if ([oneObject isKindOfClass:[CustomCell class]])
            customCell = (CustomCell *)oneObject;
}

customCell.firstLabel.text = @"Hello";
customCell.secondLabel.text = @"World!";

return customCell;
Run Code Online (Sandbox Code Playgroud)

一切正常.但是从我看过的教程中,看起来在更改标签的值时,我应该这样做:

UILabel *firstLabel = (UILabel *)[customCell.contentView viewWithTag:555];
firstLabel.text = @"Hello";

UILabel *secondLabel = (UILabel *)[customCell.contentView viewWithTag:556];
secondLabel.text = @"World!";
Run Code Online (Sandbox Code Playgroud)

(标签的标签值已在NIB中设置).

有人能告诉我哪种方法更受欢迎,为什么?

谢谢!

Mik*_*ler 13

viewWithTag: 这是一种快速而肮脏的方式来提取子视图而无需在父项上设置IBOutlet属性,甚至无需创建UITableViewCell子类.

对于非常简单的情况,这是一个可接受的解决方案,这viewWithTag:就是预期的目标.但是,如果您要重复使用该单元格,或者希望它具有更易于开发人员的界面,那么您将需要子类化并使用第一个示例中的实际属性.

因此,viewWithTag:如果它是您在IB中设计的非常简单的单元格,没有子类,只有几个标签,请使用它.使用具有真实属性的单元子类来获得更实质的内容.


cra*_*avr 10

我已经意识到,如果元素以编程方式添加到单元格中(即未在NIB中定义并通过IBOutlets连接),则使用"viewWithTag"检索元素很有用 - 这样可以防止为每个实例创建多个标签等细胞