Henry H Miao
Henry H Miao

Reputation: 3528

Instantiate custom table view cell from xib failed

Here is the inheritance tree of my table view cells.

 +----------------+
 | UITableViewCel |
 +-------+--------+
         ^
         |
 +-------+--------+
 |  BaseFormCell  |
 +-------+--------+
         ^
         |
+--------+---------+
| TypedFormCell<T> |
+--------+---------+
         ^
         |
+--------+----------+
| TextFieldFormCell |  : TypedFormCell<String>
+-------------------+

where TextFieldFormCell has an associated xib file which is used to instantiate itself.

When I call Bundle.main.loadNibNamed("TextFieldFormCell", owner: nil, options: nil), an exception is thrown and says

[< UITableViewCell 0x7fe89584fa00 > setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key nameLabel.

I noticed that the xib didn't instantiate a TextFieldFormCell for me. Instead, it created a UITableViewCell and tried to inject the nameLabel to UITableViewCell, which caused the exception.

Does this mean that IB doesn't support generic classes or classes inherit from generic classes?

Here is the GitHub repo of this demo. https://github.com/hikui/TypedCellDemo

Upvotes: 1

Views: 661

Answers (2)

Imad Ali
Imad Ali

Reputation: 3301

Another alternative way:

Register the nib file in your class viewDidLoad

    let nibName = UINib(nibName: "<nibName>", bundle:nil)
    self.tableView.registerNib(nibName, forCellReuseIdentifier: "<CellIdentifier>")

In your cellForRowAtIndexPath:

    let cell : TextFieldFormCell? = tableView.dequeueReusableCell(withIdentifier: "<CellIdentifier>") as! TextFieldFormCell?

Upvotes: 1

Usman Javed
Usman Javed

Reputation: 2455

You can add custom tableview cell by using this

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellIdentifier = "textFieldFormCell"
        var cell : TextFieldFormCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! TextFieldFormCell?
        if (cell == nil) {

            cell = Bundle.main.loadNibNamed("TextFieldFormCell", owner: nil, options: nil)?[0] as? TextFieldFormCell
        }

        cell?.backgroundColor = UIColor.clear
        cell?.contentView.backgroundColor = UIColor.clear

        return cell!
    }

Upvotes: 0

Related Questions