以编程方式将 UILabel 添加到自定义 tableViewCell

Adding UILabel to a custom tableViewCell programmatically

我正在尝试以编程方式将标签添加到自定义 table 视图单元格。该应用程序仍会崩溃并显示 '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"
}

自定义 table 视图 class 已正确分配给故事板中的原型单元格。

如果我将 MyTableViewCell 中的声明更改为 var titleLabel = UILabel() 并从 init() 中删除该行,table 视图将显示,但我的标签不会显示. 不过我觉得代码不错,关于我在这里可能遗漏的内容有什么建议吗?

您在情节提要中制作了自定义单元格,因此您无需为 table 注册 class view.And 情节提要中的视图将调用 initWithCoderawakeFromNib,请在这两个函数中添加label。