Custom table TableView: deactivation error: unexpectedly found nil

Customization

I am trying to customize a cell prototype. Here is a cell in my main storyboard.

enter image description here

I have my own cell class.

class UserListTableViewCell: UITableViewCell {
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var dateCreatedLabel: UILabel!
    @IBOutlet weak var dateOfLastLoginLabel: UILabel!
}

      

It is linked to the cell prototype in the same storyboard.

enter image description here

And just, of course, here's the custom class name in the inspector.

enter image description here

Finally, in my opinion, the controller has the following extension that implements the protocol UITableViewDataSource

.

extension UserListViewController: UITableViewDataSource {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return users.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("userListCell", forIndexPath: indexPath) as! UserListTableViewCell
        cell.nameLabel.text = users[indexPath.row].name
        return cell
    }
}

      

Along with the method viewDidLoad

.

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.dataSource = self
    tableView.tableHeaderView = tableHeaderView
    tableView.registerClass(UserListTableViewCell.self, forCellReuseIdentifier: "userListCell")
}

      

Problem

When I run this in the simulator, I get a crash when working with fatal error: unexpectedly found nil while unwrapping an Optional value

. All my labels are in the stack trace nil

.

What's going on here and how can I fix it?

+3


source to share


1 answer


Storyboard prototype cells are automatically registered for use with dequeueReusableCellWithIdentifier()

. If a cell is not available for reuse, a new instance will be created from the prototype cell (using initWithCoder:

), with all the labels and other elements that you defined in the storyboard.

FROM



tableView.registerClass(UserListTableViewCell.self, forCellReuseIdentifier: "userListCell")

      

you are replacing the registration of the prototype cell. Will now dequeueReusableCellWithIdentifier()

create an instance UserListTableViewCell

(using initWithStyle:

like @dan). But there is no connection to the prototype, so labels and other elements are not generated. In your case cell.nameLabel

nil

, and therefore accessing cell.nameLabel.text

throws an exception.

+3


source







All Articles