0

I have a custom UITableViewCell in Swift 3 (let's call it MyCustomTableViewCell) and it has an identifier "CustomCell".

If I use my custom cell without registering it for reuse, it works fine in

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! MyCustomTableViewCell

    return cell
}

If I try to register it for reuse via

override func viewDidLoad() {
   super.viewDidLoad()       

    myUITableViewThatIsIBOutlet.register(MyCustomTableViewCell.self, forCellReuseIdentifier: "CustomCell")
}

when I try to access the table I get "fatal error: unexpectedlyfound nil while unwrapping an Optional value" and the UILabels in my custom cell are showing up as "nil" (which is presumably what's causing the fatal error).

Am I doing something wrong when I register the custom cell, or am I supposed to not register a custom cell for reuse?

  • 1
    have you registered cell identifier is storyboard as well? – Tushar Sharma Aug 27 '17 at 13:44
  • The only time you need to manually register a cell for a table is when the cell is defined in a xib file instead of inside the storyboard or when you have a completely programatic cell. – allenh Aug 27 '17 at 13:50
  • If you register a cell via it's class, it must create all subviews itself. There is nothing loaded from storyboards or nibs. @TusharSharma: Registering by class has nothing to do with storyboads. – clemens Aug 27 '17 at 13:53
  • @macmoonshine I guess op has registered cell identifier from storyboard , but also trying to set programmatically which is not needed.He is not doing things programmatically instead using storyboard. – Tushar Sharma Aug 27 '17 at 13:56
  • @TusharSharma: However, this does not explain the above-mentioned error. – clemens Aug 27 '17 at 13:58
  • @macmoonshine I neither mentioned I am trying to explain one . I just asked my question. – Tushar Sharma Aug 27 '17 at 14:03
  • https://stackoverflow.com/a/25545185/5714427 check this, It gives solution – Pavankumar Aug 28 '17 at 10:08

1 Answers1

0

Yes it does if you use:

tableView.dequeueReusableCell(withIdentifier:

In your example, is it possible you have added the custom identifier to the prototype cell in your storyboard? That would explain why it works without registering manually. You need to register a custom cell so that it can be dequeued, and either approach works. You don't need both.

If this is unclear, please provide more information. I'll be happy to update my answer.

Mozahler
  • 4,958
  • 6
  • 36
  • 56
  • Ah, I did add the identifier to the prototype cell in the storyboard. I did not realize that registers the cell. Thanks for clarifying! – Jonathan Bronson Aug 27 '17 at 15:46
  • Yes, it's not obvious. But the system needs a way to find out about your cell, and Apple provides you with an IB, and a programmatic approach. – Mozahler Aug 27 '17 at 15:49