Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subclass custom Cell class with xib in swift

I got stuck with simple issue and can't find any solution.

MyCell.xib has fileowner MyCell : UITableViewCell class.

I use it like that:

viewDidLoad method:

 let nib = UINib(nibName: "MyCell", bundle: nil)
 self.tableView.register(nib, forCellReuseIdentifier: "myIdentifier")

tableView cellForRowAt method:

 let cell = tableView.dequeueReusableCell(withIdentifier: "myIdentifier", for: indexPath) as? MyCell

It works good.

I subclass my class to add some new methods:

 class SuperCell : MyCell {
      func coolMethod {
           print("cool")
      }
 }

And try to use it like that:

let cell = tableView.dequeueReusableCell(withIdentifier: "myIdentifier", for: indexPath) as? SuperCell

it returns nil

How can I make it work?

I tried to create prototype cell in InterfaceBuilder with identifier myIdentifier and with class SuperCell, but it didn't help.

Why do I need it

I just want to use the same view (xib) for different cell classes.

In my case I have common cell (MyCell) with view (xib). MyCell completely describes fields (IBOutlets). Also I want to create some another cell classes that subclasses MyCell, but they will provide some behaviour of these IBOutlets. For example FirstMyCell : MyCell will have method setFieldsFrom(objectOne: ObjectOne) and SecondMyCell : MyCell will have another method setFieldsFrom(anotherObject: ObjectAnother).

Of course, I can just add this two methods into my MyCell class, but it will be unclean.

like image 546
John Kakon Avatar asked Jan 26 '17 09:01

John Kakon


1 Answers

  • Do not set the files owner (remove it)
  • Make sure your your XIBs Custom Class is set to SuperCell:

like image 81
shallowThought Avatar answered Oct 22 '22 05:10

shallowThought