我正在使用 Xcode 版本 8.2.1 (8C1002) - 因此我相信 Swift 3 - 尝试使用默认单元格以外的单元格创建表格 View ,并且似乎无法将单元格细节文本标签或单元格 ImageView 设置为除了零之外。
我已将项目的部署目标设置为通用设备上的 9.0。
在界面生成器中,我已将内容建立为具有 1 个原型(prototype)单元的动态原型(prototype)。
在界面生成器中,我已将 TableView 单元格样式设置为“Right Detail”,其中包含图像“animal08.png”和标识符“PlayerCell”。
在 TableView 的 View Controller 中,在重写函数 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 语句时,我得到:
“ fatal error :在解包可选值时意外发现 nil”
同样,尝试访问 imageView 属性时发现 nil。
果然,print(cell.subviews.count) 语句显示该单元格只有 1 个 subview 。 除了通过界面生成器或 init(style: UITableViewCellStyle, reuseIdentifier: String?) 初始值设定项之外,我看不到设置或获取 UITableViewCell 的 UITableViewCellStyle 属性。
我相信使用 init 方法会破坏 dequeueReusableCell 的优点,因此不应在这种情况下使用。
我读到(未经证实)tableview.register 方法将 tableViewCellStyle 重置为默认值。
上面的代码似乎与 Apple 开发者网站上的样板代码以及众多贡献者提供的大量教程相同。
那么,如何访问detailTextLabel和imageView subview 并仍然使用出列的单元格?
最佳答案
您应该将单元格样式更改为 UITableViewCellStyleDefault
以外的值。据我所知,在这种情况下也不需要展开。
关于您尝试的其他内容:
顺便说一句,打印 cell.subviews.count
不会给您任何可用的值,因为 UITableViewCell
中的所有 subview 都应该添加(默认 subview 位于其 -contentView
(单元格属性)内。
同样使用使用 -initWithStyle:reuseIdentifier:
初始化的单元格没有额外的缺点,因为您仍然可以使用重用机制并同时指定所需的单元格样式。当重用 Storyboard 定义的单元格以及 Interface Builder 中指定的属性时,出队实际上更有意义。
关于ios - 在表格 View 单元格上无法访问detailTextLabel和imageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42582351/