Why UITableViewCell needs to be registered?

半城伤御伤魂 提交于 2019-12-13 10:37:21

问题


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:

Tap Add button, show a new cell with a button and a textfield.

But in my project, I use the same way, when I tap Add button, the app will crash, and report this error:

*** 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")

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.


回答1:


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")


来源:https://stackoverflow.com/questions/50445191/why-uitableviewcell-needs-to-be-registered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!