【问题标题】:detailTextLabel and imageView not accessible on table view cells在表格视图单元格上无法访问 detailTextLabel 和 imageView
【发布时间】:2017-07-23 18:26:38
【问题描述】:

我正在使用 Xcode 版本 8.2.1 (8C1002) - 因此我相信 Swift 3 - 尝试使用非默认单元格制作表格视图,并且似乎无法获取单元格 detailTextLabel 或单元格 imageView除了零。

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

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

在界面构建器中,我已将表格视图单元格样式设置为“右细节”,其中包含图像“animal08.png”和“PlayerCell”标识符。

在表视图的视图控制器中,在覆盖函数 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 属性的尝试结果为零。

果然,print(cell.subviews.count) 语句显示单元格只有1个子视图。 除了通过界面生成器或 init(style: UITableViewCellStyle, reuseIdentifier: String?) 初始化程序之外,我看不到 UITableViewCell 的 UITableViewCellStyle 属性的设置或获取。

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

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

上述代码似乎与 Apple 开发者网站上的样板代码和众多贡献者提供的大量教程相同。

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

【问题讨论】:

  • 创建一个具有图像视图和两个标签的自定义表格视图单元格或更改 uitableviewcell 的样式
  • “正确的详细信息”表视图单元格没有详细信息文本标签,并且(它确定,从未尝试过)您无法设置正确的详细信息项目(当您将图像视图设置为你在上面的代码中做了你在左边设置了(也在这个不存在的)图像视图。当@Fahad 建议创建一个自定义表格视图单元格时,他是绝对正确的。

标签: ios swift uitableview tableviewcell


【解决方案1】:

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

关于你尝试的其他东西:

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

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

【讨论】:

  • 嗯,我刚刚在 Swift Playground 中进行了测试,代码在所有可能的单元格样式中都运行良好,没有代码崩溃,包括 .default 样式。 import UIKit import PlaygroundSupport let c = UITableViewCell(style: .value2, reuseIdentifier: nil) c.backgroundColor = UIColor.white c.textLabel?.text = "Text" c.detailTextLabel?.text = "Detail" PlaygroundPage.current.liveView = c
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
相关资源
最近更新 更多