我正在尝试通过编程方式向自定义表格视图单元格添加标签。 应用程序仍会崩溃并显示 'unexpectedly found 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)
}
}
在视图控制器内部:
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"
}
定制的表格视图类已正确分配给故事板中的原型单元格。
如果我更改
MyTableViewCell
内部的声明为 var titleLabel = UILabel()
并从 init()
中删除该行,则表格视图将显示但我的标签不会显示出来。
虽然代码看起来很好,但您有什么建议或可能错过了什么?
titleLabel
属性使用let
。这样,在调用super.init(...)
之前,您可以初始化它。尽可能避免使用隐式解包可选项,因为它允许您获取精确的错误信息。 - AdamPro13registerClass:forCellReuseIdentifier:
否则那个出列方法将会失败。 - AdamPro13viewDidLoad()
中添加了那行代码:tableView.registerClass(ListTableViewCell.self, forCellReuseIdentifier: "SongItem")
。它起到了作用!虽然我之前已经使用自定义单元格调用过这个方法,但是当时没有为单元格创建标签属性。不过这个解决方案有一个副作用:现在编译器不满意我在Storyboard中添加的其他标签引用和使用viewWithTag()
获取的标签。所以,是要么通过编程方式实现,要么通过Storyboard实现单元格? - nontomaticsuper.init(coder: aDecoder)
并出现错误:_'Property 'self.titleLabel' not initialised at super.init call'_。这就是为什么我将其改为这样的原因。另外,如果您将其发布为答案,我可以接受! - nontomatic