Sub-classing UIView is so dizzy 🤯

Back to the time I use Objective-c to write most of the applications for iOS. Creating a custom UIView was so easy, if you are familiar with OOP, you would not encounter any problems while doing it. But in Swift, it is just crazy complicated since I cannot just make one initializer alone, it requires some confusing overloading functions that make no sense.

This is what I expected, If I use the same methodology, It should work perfectly in Objective-C.

But Xcode cannot compile the piece of code above. Here goes what It says:

1. required ‘initializer ‘init(coder:)’ must be provided by subclass of ‘UIView’?

First, init(coder:) must be provided???. Why we need to care about that initialization method which should belong to the UIView base class itself. We can fix that error by following the introduction given in the error message: override base’s method init:(coder:)

So, why put fatalError in init(coder:)?

When creating UIView subclasses that will never be used in a storyboard or nib, you might introduce initializers with different parameters and initialization requirements that could not be called by the init(coder:) method. If you did not fail init(coder:) with a fatalError, it could lead to very confusing problems down the line if accidentally used in a storyboard/nib. The fatalError asserts these intentions.

2. Must call a designated initializer of the superclass ‘UIView’?

If you look into UIView’s interfaces, there are only 2 initialization method that allow child’s class to override, and there is no such as init() without parameters. So, we could call superclass’s method init(frame:) with default value is a rectangle (0,0).

3. Property ‘self.name’ not initialized at super.init call?

In Objective-C where [super init] would typically be called first before anything else, It couldn’t apply to Swift. In Swift, calling super’s init(…) in initializaton must be the reverse, mean you are responsible for ensuring that your instance variables are in a consistent state before you do anything else, including calling methods (which includes your superclass’ initializer).

3. Finish

Hoorayy, finally we successfully subclass UIView. It is a little bit confusing but I believe that with above explaination, it would help you subclassing an UIView successully at the first time you compile ;), Good luck!

Leave a Comment

Your email address will not be published. Required fields are marked *