在以编程方式实例化的 Table 视图控制器中注册一个单元格

Register a cell in programmatically instanciated Table View Controller

我收到这个错误:

'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier NavigationNodeCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

我正在使用两个具有相同 class "NavigationItemCell" 和两个标识符 "NavigationNodeCell" 和 "NavigationLinkCell".

的单元格

然后我创建了一个单元格,例如:

let cell: NavigationItemCell  = self.tableView.dequeueReusableCellWithIdentifier("NavigationNodeCell",     forIndexPath: indexPath) as! NavigationItemCell

这个问题在我之前就存在过,例如Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

据我所知(例如 Sebastian Borggrewe 的回答者)在故事板中注册一个 UITableViewCell 及其自定义 class 和一个标识符就足够了。

这正是我所做的,但我仍然收到此错误。 我尝试使用两个不同的 classes 但它没有解决错误。 我也尝试用 nib 注册我的单元格,但我 运行 遇到其他问题(标签为零)。

我发现这个问题可能会发生,因为我以编程方式实例化了一个新的 table 视图控制器。

var newController = MyTableViewController()

这是否意味着我无论如何都必须注册 nib?我必须注册相同的 class 两次,这是个问题吗?以及如何避免nil标签的问题?

您应该使用故事板 ID 创建视图控制器的实例。 将行 var newController = MyTableViewController() 替换为以下代码

let storyboard = UIStoryboard(name: "YOUR_STORYBOARD_NAME", bundle: nil)
let newController = storyboard.instantiateViewController(withIdentifier: "VIEWCONTROLLER_ID_FROM_STORYBOARD")

编辑: 也可以使用: self.storyboard!.instantiateViewControllerWithIdentifier("VIEWCONTROLLER_ID_FROM_STORYBOARD")

如果视图控制器是从情节提要中实例化的,并且第二个视图控制器在同一个情节提要中

如果您使用初始化程序(而不是 storybaord.instantiateViewController(withIdentifier:))创建 table 视图控制器,那么您的 table 视图控制器将不知道您放入情节提要中的单元格。如果您想使用初始化程序,则需要在控制器的 viewDidLoad.

中手动注册自定义单元格 class
class MyTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad
        tableView.register(NavigationNodeCell.self, forCellReuseIdentifier: "NavigationNodeCell")
    }

}