简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM