When we are subclassing UIView() to create a view programmatically in Swift we are faced with a required init?(coder) that defaults to fatalError() if not implemented. Some practices employ that ignoring the implementation is okay since the code is being done programmatically and interface builder or nibs won’t be called.
Question is what if you want to reuse this subclass code that you have written? One of the benefits of encapsulating view code in a subclass is to be able to reuse it in another code base as needed. So it would be counterintuitive if we were not able to extend this class, say we what to implement our subclass view in a storyboard.
Let’s see such a case where we want to use a storyboard and the subclass BestSellerView() we have written in code.
TestViewController is being made the root view controller in the AppDelegate
TestViewController storyboard view subclasses our custom BestsellersView()
In the screenshot below the app crashes on line 49 if the init?(coder) is not implemented and the TestViewController’s view is subclassed from the BestsellersView().
However if we use a helper method e.g a method named commonInit() that shared initialization code between init(frame) and init?(coder) our subclass view code now is extensible to be used in a storyboard/nib or programmable ui code.
Example Code Snippet showing helper method commonInit()
override init(frame: CGRect) {
super.init(frame: UIScreen.main.bounds)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = .white
setupViews()
}
Conclusion
When subclassing UIView() make sure to use a helper method to have either init(frame) or init?(coder) called as per caller UI implementation (storyboard/nib or code).