1
votes

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.

3
BTW: UITableViewController has a property for the table view already.clemens

3 Answers

3
votes

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.

2
votes

You are using the UITableView instance method:

func register(AnyClass?, forCellReuseIdentifier: String)

This only works if your custom UITableViewCell subclass is not setup using Interface Builder

If you've created your subclass using an xib. You should use:

func register(UINib?, forCellReuseIdentifier: String)

like:

let nib = UINib(nibName: "\(TodoTableViewCell.self)", bundle: nil)
self.tableView.register(nib, forCellReuseIdentifier: "TodoTableViewCell1")

If you're using prototype cells in a storyboard you don't need to register your cells at all.

0
votes

I think the identifier of the cell should be in the identifier from the attributes inspector column not the Identity inspector and in module in Identity inspector add your project