自定义TableView单元格出列致命错误:意外发现为零

时间:2015-07-16 20:15:50

标签: ios swift uitableview

设置

我正在尝试自定义原型单元格。这是我主要故事板中的单元格。

enter image description here

我有一个自定义单元格类。

 non-transient entity has a null id

它与同一故事板中的原型单元相关联。

enter image description here

只是确定,这是检查器中的自定义类名。

enter image description here

最后,在我的视图控制器中,我有以下扩展来实现class UserListTableViewCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var dateCreatedLabel: UILabel! @IBOutlet weak var dateOfLastLoginLabel: UILabel! } 协议。

UITableViewDataSource

extension UserListViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("userListCell", forIndexPath: indexPath) as! UserListTableViewCell cell.nameLabel.text = users[indexPath.row].name return cell } } 方法一起使用。

viewDidLoad

问题

当我在模拟器中启动它时,override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.tableHeaderView = tableHeaderView tableView.registerClass(UserListTableViewCell.self, forCellReuseIdentifier: "userListCell") } 会导致运行时崩溃。在堆栈跟踪中,我的所有标签都是fatal error: unexpectedly found nil while unwrapping an Optional value

这里发生了什么,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

故事板原型单元格会自动注册使用 与dequeueReusableCellWithIdentifier()。如果没有可用的单元格 重用,一个新的将从原型单元格(使用initWithCoder:)实例化,所有标签和其他元素,你 在故事板中定义。

使用

tableView.registerClass(UserListTableViewCell.self, forCellReuseIdentifier: "userListCell")

替换原型单元的注册。现在 dequeueReusableCellWithIdentifier()将创建一个实例 UserListTableViewCell(使用initWithStyle:作为@dan说)。但那里 没有连接到原型单元格,所以标签和其他元素 没有创建。在您的情况下,cell.nameLabelnil,因此 访问cell.nameLabel.text会引发异常。

相关问题