How to subclass custom Cell class with xib in swift
Asked Answered
B

1

9

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.

Beckwith answered 26/1, 2017 at 9:38 Comment(5)
why whould you want to subclass a custom cell ?Hothouse
@UmairAfzal please look my updateBeckwith
@JohnKakon did you find a way to subclass using same xib.Mccourt
@JohnKakon Did you find any solution for this?Potamic
@JohnKakon Did you resolve your problem ?Peruse
A
2
  • Do not set the files owner (remove it)
  • Make sure your your XIBs Custom Class is set to SuperCell:

Arminius answered 26/1, 2017 at 9:54 Comment(4)
What If I will have SuperClass : MyClass and SecondSuperClass : MyClass with the same xib? Which one should I set in InterfaceBuilder? MyClass?Beckwith
That does not make sense to me. Maybe update your question and describe your use case, what you want to achieve, more detailed.Arminius
Are you saying that there is no additional code required inside 'MyClass.swift' ?Avoidance
Only code is let cell = tableView.dequeueReusableCell(withIdentifier: "myIdentifier") as? SuperCell. You certainly need to set outlets for Labels or such to MyCellClass.Arminius

© 2022 - 2024 — McMap. All rights reserved.