-3

I have two view controllers, one of them part being a side menu. I try to init its cells with data from an array but I keep having errors when trying to assign a value to a cell label text. Here is the code I have:

class TableViewCell: UITableViewCell {
    @IBOutlet weak var cellImage: UIImageView!
    @IBOutlet weak var cellLabel: UILabel!
}


class SideMenuTableViewController: UITableViewController {
    let vc = ViewController()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        tableView.reloadData()

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return vc.array.count

    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        let myImage = UIImage(named: "checkbox")
        cell.cellLabel.text = "test" //HERE IS THE ERROR
        cell.cellImage.image = myImage
        return cell
    }

}

And here is the error.

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

In the debugger, I can see that my cell contains the label and image from the Sotryboard but I cannot assign myImage and any text to the cell. What am I doing wrong? Thanks in advance for your help.

radar
  • 500
  • 1
  • 6
  • 24
  • 2
    Which line exactly is causing the crash? Are the outlets connected in the cell? – rmaddy Jan 28 '18 at 17:53
  • Thanks @maddy, I had not connected the outlets. – radar Jan 28 '18 at 20:56
  • Possible duplicate of https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu?s=1|489.4274 – rmaddy Jan 28 '18 at 23:39

2 Answers2

2

seems like

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

is causing the crash. Did you remember to set the class of your cell prototype in Storyboard to TableViewCell?

dinosaysrawr
  • 348
  • 2
  • 15
1

Check :
1. Custom cell has reusableCellIdentifier set in xib.

enter image description here

  1. If you are using xib for custom cell, custom cell should be registered with UITableView :

tableView.register(TableViewCell.self, forCellReuseIdentifier: "yourIdentifier")

Nitish
  • 13,845
  • 28
  • 135
  • 263