1

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

Henry H Miao
  • 3,420
  • 4
  • 20
  • 26
  • this means your xib name is not correct. Can you check "TextFieldFormCell" is really the correct name you passed in Bundle.main.loadNibNamed("TextFieldFormCell", owner: nil, options: nil) – aman.sood Dec 26 '16 at 09:27
  • chcek this answer http://stackoverflow.com/questions/40275727/is-it-possible-to-create-one-tableviewcell-that-can-be-used-in-multiple-table-co/40277758#40277758 – Umair Afzal Dec 26 '16 at 09:34
  • @aman.sood I've checked it multiple times. – Henry H Miao Dec 26 '16 at 10:21
  • IB works with Obj-C runtime. So using a generic table view cell in storyboard won't work. – T. Pasichnyk Jul 13 '17 at 12:32

2 Answers2

1

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?
Imad Ali
  • 3,261
  • 1
  • 25
  • 33
0

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!
    }
Usman Javed
  • 2,437
  • 1
  • 17
  • 26