I want to reuse a UITableViewCell in my app, but I get this error: Unexpectedly found nil while implicitly unwrapping an Optional value.

I find that this is because the UI things in UITableViewCell is nil, so my app crashed.

My UITableViewCell code is like this:

class WordListCell: UITableViewCell {

    @IBOutlet weak var wordListCoverImage: UIImageView!
    @IBOutlet weak var wordListName: UILabel!
    @IBOutlet weak var wordListInfo: UILabel!

    var wordList: WordList? {
        didSet {
            updateUI()
        }
    }

    private func updateUI() {
        wordListName.text = wordList?.name
        wordListInfo.text = wordList?.description
        wordListCoverImage = UIImage()
    }
}

I create it in the storyboard and link the outlet to the code in the other TableView.

But this time, I want to reuse the cell in a new TableView which is all created by code, so I don't know how to initialize the UI things.

The new UITableView code is like this:

tableView.delegate = self
tableView.dataSource = self
tableView.register(WordListCell.self, forCellReuseIdentifier: "wordListCell")

//the delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return wordLists.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let wordList = wordLists[indexPath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: "wordListCell", for: indexPath)
    if let wordListCell = cell as? WordListCell {
        wordListCell.wordList = wordList
    }

    return cell
}

Please tell me how to reuse the cell.Thanks!

1 Answers

1
Defkalion1 On

Okay so I think what you are doing wrong is when you create a custom tableView cell, you are not assigning a UIImage. So instead try doing this wordListCoverImage = UIImage(named: wordList.imageName).

Now also in your tableView class inside viewDidLoad() apart from adding

tableView.delegate = self
tableView.dataSource = self
tableView.register(WordListCell.self, forCellReuseIdentifier: "wordListCell")

Then at let cell = tableView.dequeueReusableCell(withIdentifier: "wordListCell", for: indexPath) downcast it as a custom cell class like so.

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

And then finaly under that set the cell.delegate = self

I hope this helps!