Search code examples
iosswiftuitableviewswift3

Register UITableViewCell not working


I am trying to register UITableViewCell in viewdidload

self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")

In cellForRowAtIndex

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell  

    cell.productNameLabel.text = "Product"
    cell.productNameLabel.textColor = UIColor.darkGray

    return cell
}

Here it is crashing in cell.productNameLabel.text.

What is the purpose of registering cell? why it is crashing? I want to reload data even if cell or table is not visible.

Crashreport : enter image description here


Solution

  • See the Apple's comments which answers your query on the purpose of registering cell :

    Prior to dequeueing any cells, call this method or the register(_:forCellReuseIdentifier:) method to tell the table view how to create new cells. If a cell of the specified type is not currently in a reuse queue, the table view uses the provided information to create a new cell object automatically.

    This is the standard procedure I apply while working with Custom Cells (if you are using xib) :

    1. Set cell's identifier in Xib's attribute inspector :

    enter image description here

    1. Register Xib :

      self.tableTasks.register(UINib(nibName: "TaskCell", bundle: nil), forCellReuseIdentifier: "taskCell")
      

    However, if you are not using Xib and creating custom cell using code only, then use registeCell :

    self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")