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

标签 ios iphone uitableview

有人可以解释为什么你应该使用 viewWithTagdequeueReusableCellWithIdentifier 中的单元格获取 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/

相关文章:

objective-c - 禁用 MKmapkit mapView userLocation annotationView

ios - 为什么我的 iphone swift 应用程序分配并使用大量内存?

iPhone MapKit - 同时删除多个图钉

iphone - iPhone 应用程序中的 UIWindow 是在哪里实例化的?

ios - 带有 TableView 和非滚动页脚 View 的 UITableViewController

iphone - heightForRowAtIndexPath 用于更长的 NSString

ios - 尽管我以编程方式选择了一个单元格,但 indexPathForSelectedRow 返回 nil

iphone - 如何在 iPhone 中使用 DES 加密 NSString 值?

ios - 当从 Firebase 控制台更改数据时,如何在 Firebase 上执行多路径数据更新?

ios - 如何分离 iOS APNS 通知的沙箱和生产设备 token