考虑下面的简单视图控制器:

class ViewController: UIViewController, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    var items = ["One", "Two", "Three"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")
        self.tableView.dataSource = self
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
        cell.titleLabel!.text = self.items[indexPath.row]
        return cell
    }
}

和自定义单元格视图:

class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var titleLabel: UILabel!   
}

此代码导致以下错误.

致命错误:在展开可选值时意外发现nil

titleLabel是零——不清楚为什么.将默认属性设置为UITableViewCell(比如textLabel)效果很好.

我用笔尖做定制电池.

标签和表格视图都已正确连接到它们的IBOutlet.

label table view

原型单元和定制nib视图都被标记为具有CustomTableViewCell类.

我是iOS开发新手,我是不是错过了一些明显的东西?

Sample Xcode project available

推荐答案

首先,使用nib文件将自定义单元格加载到表中.如果你刚刚接触Swift/Cocoa,这可能会让你头疼不已.我会暂时把一切转移到故事板上.不要使用nib文件,点击进入故事板,点击UITableView,确保TableView的内容设置为Dyanamic Prototypes:

在此处输入图像描述

接下来,单击prototype单元(表视图中唯一的一个),将类设置为CustomTableViewCell,并将其重用标识符设置为customCell:

enter image description here enter image description here

接下来,在原型单元中添加一个标签,并将其链接到CustomTableViewCell类中的IBOutlet.只要在情节提要中设置了重用标识符,就不需要注册customCell.删除这一行:

self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")

它应该运行.

Swift相关问答推荐

如何在SWIFT任务中判断当前任务是否已取消(异步/等待)

出错-无法将季节类型的值转换为预期的参数类型';[水果]';

字典下标或运算符,如果密钥不存在,则添加指定的默认&值是SWIFT?

Swift中从头开始的基本HTTP客户端

Swift:结果的失败类型不能是协议 - Type 'any ShadowError' cannot conform to Error

使用 WrappingHStack 文本溢出到新行

快速更改tableView中的数据

数组使用偏移量对自身执行 XOR

为什么更改属性后动画会加速? SwiftUI

在 xcode 13 中的构建之间保持可访问性权限

Swift - 如何更新多目录中的对象

仅在 Swift 中创建 Setter

无法使用锚激活约束

Swift 覆盖实例变量

subscribeOn 和 observeOn 的顺序重要吗?

MKAnnotation Swift

两个 Date 对象之间的所有日期 (Swift)

在 Swift 中指定 UITextField 的边框半径

Swift中方法的弃用和其他属性,如何?

如何快速格式化用户显示(社交网络等)的时间间隔?