Why is it best practice to implement init?(coder) when subclassing UIView()

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

screen shot 2019-01-26 at 7.01.14 am

TestViewController storyboard view subclasses our custom BestsellersView()

screen shot 2019-01-26 at 7.00.08 am

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().

screen shot 2019-01-26 at 6.59.02 am

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).

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s