为什么需要注册UITableViewCell? [英] Why UITableViewCell needs to be registered?
问题描述
这些都是我演示中的所有代码:
these are all codes in my demo:
import UIKit
class TableViewController: UITableViewController {
var numberOfCell = 0
@IBAction func addAction() {
numberOfCell = numberOfCell + 1
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfCell + 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath)
let addButton = cell.viewWithTag(99) as! UIButton
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "SecondCell", for: indexPath)
let deleteButton = cell.viewWithTag(100) as! UIButton
let textField = cell.viewWithTag(101) as! UITextField
return cell
}
} else {
return super.tableView(tableView, cellForRowAt: indexPath)
}
}
}
我在故事板文件的属性检查器中设置了单元格的标识符,没有注册单元格,一切正常像这样:
I set cells' identifier in Attributes inspector at storyboard file, didn't register the cells, everything goes right like this:
但是在我的项目中,我使用相同的方式,当点击添加按钮时,应用程序将崩溃,并报告此错误:
But in my project, I use the same way, when I tap Add button, the app will crash, and report this error:
***由于未捕获的异常而终止应用程序
'NSInternalInconsistencyException',原因:无法将具有标识符SecondCell的单元
出队-必须为该标识符
注册一个笔尖或一个类,或将一个原型单元连接到情节提要'
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier SecondCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
我尝试过注册单元使用此代码:
I have tried register cell use this code:
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "SecondCell")
但是,如果执行此操作,应用程序将在 let deleteButton = cell.viewWithTag(100)崩溃! UIButton
和 let textField = cell.viewWithTag(101)为! UITextField
因为它们为零。
But if I do this, the app will crash at let deleteButton = cell.viewWithTag(100) as! UIButton
and let textField = cell.viewWithTag(101) as! UITextField
because them are nil.
我认为我的项目和演示没有区别,我不知道该如何处理。
I think my project and demo have no differences, I don't know how to deal with this issues.
推荐答案
如果您使用的是nib文件,则需要在表格视图中注册单元格。
If you are using nib file then you need to register your cell in the tableview.
self.tableView.register(UINib(nibName: "nibName", bundle: nil), forCellReuseIdentifier: "CellIdentifier")
这篇关于为什么需要注册UITableViewCell?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!