Search code examples
iosswiftxcodeuitableviewtableview

Custom view cell always has properties set to nil (UITableView)


Table view cell in cellForRowAt alway has all properties set to nil

import UIKit

class TodoTableViewCell: UITableViewCell {
    @IBOutlet weak var label: UILabel!
}

class TodosViewController: UITableViewController {

    @IBOutlet var TodosTableView: UITableView!
    var projects = [Project]()
    var todos = [Todo]()

    override func viewDidLoad() {
        super.viewDidLoad()
        TodosTableView.delegate = self
        self.tableView.register(TodoTableViewCell.self, forCellReuseIdentifier: "TodoTableViewCell1")
        // data init
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "TodoTableViewCell1"
        var todo = projects[indexPath.section].todos[indexPath.row]
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TodoTableViewCell else {
            fatalError("The dequeued cell is not an instance of MealTableViewCell.")
        }

        cell.label?.text = todo.text // cell.label is always nil
        return cell
    }
}

outlet class

identifier identifier

It seems like identical issue Custom table view cell: IBOutlet label is nil

What I tried to do: - restart Xcode - recreate outlet - clean project - recreate view cell from scratch like here https://www.ralfebert.de/ios-examples/uikit/uitableviewcontroller/custom-cells/

Please help, iOS development drives me nuts already.


Solution

  • You don't need to register the class in the tableview if you're using prototype cells in Interface Builder. Try removing the registration function from viewDidLoad. Incidentally you can also set dataSource and delegate in IB - much neater code-wise.