aircraft aircraft - 1 month ago 6
iOS Question

Create tableView by storyboard use custom tableViewCell form xib get Assertion failure

Create

tableView
by
storyboard
, and in the
tableView delegate
method:
tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
occurs a exception:

*** Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:],
/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3599.6/UITableView.m:6593


my code is below:

ViewController11


@IBOutlet weak var tableView: UITableView! // tableView

// tableview delegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell_id: String = "cell_id"
// this line below occurs exception: Thread 1:breakpoint 5.2
var cell: TableViewCell2 = tableView.dequeueReusableCell(withIdentifier: cell_id, for: indexPath) as! TableViewCell2

if cell == nil {

//
}

var title = dataSource[indexPath.row]

cell.titlelabel?.text = String(title)


return cell
}


and my
storyboard
for
ViewController11
:

viewController11

and my
xib
for
TableViewCell2
:

TableViewcell12

Answer

You have to register your UITableViewCell from the xib before you can use it:

Swift 2:

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.registerNib(UINib(nibName: "TableViewCell2", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "cell_id")
}

Swift 3:

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.register(UINib(nibName: "TableViewCell2", bundle: Bundle.main), forCellReuseIdentifier: "cell_id")
}
Comments