在 table 个视图单元格上无法访问 detailTextLabel 和 imageView

detailTextLabel and imageView not accessible on table view cells

我正在使用 Xcode 版本 8.2.1 (8C1002) - 因此我相信 Swift 3 - 尝试使用非默认单元格创建 table 视图,并且似乎无法让单元格 detailTextLabel 或单元格 imageView 不是 nil。

我已经在通用设备上将项目的部署目标设置为 9.0。

在界面生成器中,我已将内容建立为具有 1 个原型单元格的动态原型。

在界面生成器中,我已将 Table View Cell Style 设置为“Right Detail”,图像为“animal08.png”,标识符为“PlayerCell”。

在 table 视图的视图控制器中,在覆盖 func viewDidLoad():

self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "PlayerCell")

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell")!
    print(cell.subviews.count)
    cell.textLabel!.text = "Name: " + myNames[indexPath.row]
    cell.detailTextLabel!.text = "Ranking: " + myRankings[indexPath.row].description
    let avatarIndex = indexPath.row + 1
    let avatarIndexName = "animal0" + avatarIndex.description
    cell.imageView!.image = UIImage.init(named: avatarIndexName)

    return cell;
}

当我 运行 在 iPhone 5 iOS 5.2(13C75) 模拟器上运行程序时,当我到达“cell.detailTextLabel!.text 语句时,我得到:

“致命错误:在展开可选值时意外发现 nil”

同样,访问 imageView 属性 的尝试结果为 nil。

果然,print(cell.subviews.count) 语句显示单元格只有 1 个子视图。 除了通过界面生成器或在 init(style: UITableViewCellStyle, reuseIdentifier: String?) initializer.

我认为使用 init 方法会破坏 dequeueReusableCell 的优势,因此不应在这种情况下使用。

我已经阅读(没有证实)tableview.register 方法将 tableViewCellStyle 重置为默认值。

以上代码似乎与 Apple Developer 网站上的样板代码以及众多贡献者提供的大量教程相同。

那么,我怎样才能访问 detailTextLabel 和 imageView 子视图并仍然使用出列的单元格?

您应该将单元格样式更改为 UITableViewCellStyleDefault 以外的值。在这种情况下 AFAIK 也不需要展开。

关于您尝试的其他内容:

顺便说一句,打印 cell.subviews.count 不会给你任何可用的值,因为 UITableViewCell 中的所有子视图都应该 添加(默认子视图是)在其 -contentView(单元格 属性)内。

使用 -initWithStyle:reuseIdentifier: 初始化的单元格也没有额外的缺点,因为您仍然可以使用重用机制并同时指定所需的单元格样式。当重用具有在 Interface Builder 中指定的属性的 Storyboard 定义的单元格时,出队实际上更有意义。