I've created a custom view using a .xib file for the layout. I would like to programatically create and add this view as a subview to a different view.
Subview class:
class Subview: UIView {
@IBOutlet var view: UIView!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var textLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
Bundle.main.loadNibNamed("Subview", owner: self, options: nil)
self.addSubview(view)
view.frame = self.bounds
}
}
I'm not sure how to go about it, the only constructor currently expects an instance of NSCoder which I don't have.
I've tried to give it an additional initialiser:
init(title: String, text: String) {
titleLabel.text = title
textLabel.text = text
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
}
And then call it:
let v = Subview(title: dataSource[i].whatever, text: dataSource[i].bla)
But it fails when trying to unwrap the label outlets, which makes sense as the .xib hasn't been initialised.
I've already tried using a tableview and custom cells instead of programatically building the UI for the page, it doesn't really work because this is a detail page and I only have a single object as my data source instead of the array which the rowForIndexPath tableview delegate expects. I know I could write some mapper method to turn the object into an array of it's properties but I'd rather avoid that if possible.
Thanks.