我正在尝试以编程方式将标签添加到自定义表格 View 单元格。该应用程序仍会因“意外发现 nil”而崩溃。我在这里查看了其他帖子,但看不出我做错了什么。详情请看代码。
import UIKit
class MyTableViewCell: UITableViewCell {
var titleLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel = UILabel()
titleLabel.textColor = UIColor.blackColor()
titleLabel.font = UIFont.systemFontOfSize(17)
titleLabel.frame = CGRect(x: 40.0, y: 2, width: bounds.width, height: bounds.height)
addSubview(titleLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
在 View Controller 中:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! MyTableViewCell
// Crashes the app with: 'fatal error: unexpectedly found nil while unwrapping an Optional value'
cell.titleLabel.text = "Some text"
}
自定义 TableView 类已正确分配给 Storyboard 中的原型(prototype)单元格。
如果我将 MyTableViewCell
中的声明更改为 var titleLabel = UILabel()
并从 init()
表中删除该行将显示 View ,但不会显示我的标签。
不过,代码对我来说看起来不错,关于我在这里可能遗漏的内容有什么建议吗?
最佳答案
您在 Storyboard中创建了自定义单元格,因此您无需为 TableView 注册类。 Storyboard中的 View 将调用 initWithCoder
和 awakeFromNib
,请添加标签在这两个函数中。
关于ios - 以编程方式将 UILabel 添加到自定义 tableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928174/