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.

Community
  • 1
  • 1
John Kakon
  • 2,531
  • 4
  • 24
  • 28

1 Answers1

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

shallowThought
  • 19,212
  • 9
  • 65
  • 112
  • What If I will have `SuperClass : MyClass` and `SecondSuperClass : MyClass` with the same xib? Which one should I set in InterfaceBuilder? `MyClass`? – John Kakon Jan 26 '17 at 10:02
  • That does not make sense to me. Maybe update your question and describe your use case, what you want to achieve, more detailed. – shallowThought Jan 26 '17 at 10:04
  • Are you saying that there is no additional code required inside 'MyClass.swift' ? – Marmelador Jun 05 '17 at 07:47
  • Only code is `let cell = tableView.dequeueReusableCell(withIdentifier: "myIdentifier") as? SuperCell`. You certainly need to set outlets for Labels or such to `MyCellClass`. – shallowThought Jun 05 '17 at 12:54