有人可以解释为什么你应该使用 viewWithTag
从 dequeueReusableCellWithIdentifier
中的单元格获取 subview (例如 UILabel
等)吗?
一些背景信息:我有一个自定义的 UITableViewCell
,里面有几个 UILabel
(我在下面复制了一个简单的版本)。这些标签在关联的 NIB 文件中定义,并使用 IBOutlet
声明并链接回自定义单元的 Controller 类。在 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!";
(标签的tag值已经在NIB中设置)
谁能告诉我首选哪种方法以及为什么?
谢谢!
最佳答案
viewWithTag:
只是一种拉出 subview 的快速而肮脏的方法,无需在父 View 上设置 IBOutlet 属性,甚至无需创建 UITableViewCell 子类。
对于非常简单的情况,这是一个可以接受的解决方案,这就是 viewWithTag:
的目的。但是,如果您打算大量重用该单元格,或者您希望它具有对开发人员更友好的界面,那么您将需要像第一个示例中那样子类化并使用真实属性。
因此,如果它是您在 IB 中设计的非常简单的单元格,没有子类且只有几个标签,请使用 viewWithTag:
。将具有真实属性的单元子类用于更实质性的内容。
关于ios - 为什么将 "viewWithTag"与 "dequeueReusableCellWithIdentifier"一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3632683/