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

标签 ios swift uilabel tableviewcell

我正在尝试以编程方式将标签添加到自定义表格 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 将调用 initWithCoderawakeFromNib,请添加标签在这两个函数中。

关于ios - 以编程方式将 UILabel 添加到自定义 tableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928174/

相关文章:

ios - 无法让 UILabels 出现在动态创建的 UIViews 上

当应用程序通过链接点击打开时,iOS 13 无法处理通用链接点击

ios swift - 具有多个数据源/ Nib 的表格 View

swift - 如何为 xib 文件内的元素设置圆角半径

ios - 避免在 Swift 中重复元组

ios - 即使文本只有一行,多行 UILabel 高度也会增加

ios - 在 Swift 中将证书添加到 IOS Keychain

ios - 如何将 SFSafariViewController 与 SwiftUI 一起使用?

arrays - 具有惰性元素的数组

swift - 部分标签可点击并同时加粗