I want to use static cells in a UITableView
in my storyboard.
But also I want those cells to be loaded from a custom .xib
file with a custom UITableViewCell
subclass.
I want to do this because I want to reuse the cells in multiple table views.
So I added some static cells in storyboard and set the custom class in the identity inspector.
But when I want to access the Outlets in the custom view's awakeFromNib
method, they are nil
. Even later, they're not beeing instantiated.
How can I do this the right way?
Ok I figured it out, how this is possible:
I created a container class for my UITableViewCell
as it is described in this answer:
https://stackoverflow.com/a/34881072/4846592
This class contains a property to get access to the custom cell and loads the XIB in its initializer
Here's the code for Swift 3
class CustomTableViewCellContainer: UIView {
var cell: CustomTableViewCell!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
cell = Bundle.main.loadNibNamed("CustomTableViewCell", owner: self, options: nil)!.first as! TextFieldTableViewCell
cell.frame = self.bounds
cell.autoresizingMask = [.flexibleWidth]
self.addSubview(cell)
}
}
Then, I just added a UIView
into the ContentView of a static UITableViewCell
in the Storyboard and set the height and CustomTableViewCellContainer
as custom class name.
Finally I added an IBOutlet
to it to get access to the custom cell.