有人可以解释为什么要使用viewWithTag从dequeueReusableCellWithIdentifier中的单元格中获取子视图(例如UILabel等)?
一些背景信息:我有一个自定义UITableViewCell与它的几个UILabels(我已经转载了下面的简单版本).这些标签在相关的NIB文件中定义,并使用IBOutlet声明并链接回自定义单元的控制器类.在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;
一切都很好但是从我看到的教程中,看起来像改变标签值时,我应该这样做:
UILabel *firstLabel = (UILabel *)[customCell.contentView viewWithTag:555]; firstLabel.text = @"Hello"; UILabel *secondLabel = (UILabel *)[customCell.contentView viewWithTag:556]; secondLabel.text = @"World!";
(标签的标签值已在NIB中设置).
有人可以告诉我哪种方法是首选,为什么?
谢谢!
解决方法
viewWithTag:只是一个简单而肮脏的方式来拉出子视图,而不必在父项上设置IBOutlet属性,甚至无需创建一个UITableViewCell子类.
对于非常简单的情况,这是一个可以接受的解决方案,这就是viewWithTag:打算用的.但是,如果要重用该单元格或者想要更多的开发人员友好的界面,那么您将需要在第一个示例中子类化并使用真正的属性.
所以使用viewWithTag:如果它是一个非常简单的单元格,你在IB中设计,没有子类,只有几个标签.使用具有真实属性的单元格子类更实质.