Search code examples
iosuiviewswiftobject-initializers

Adding additional init code to an inherited initializer from superclass


I have a Swift UIView class (named HypnosisView) that draws a circle on the screen. The frame of the view is set to fill the screen. I would like to programmatically set the background color of the view upon initialization (so when an instance of the view is created it automatically has the specified background color). I was able to make this work with a convenience initializer, however I'm wondering if there is a more efficient way to do this (or if in fact I'm doing this correctly). In an ideal scenario, I would like to just add a piece of code that sets the background: self.background = UIColor.clearColor() to the inherited init(frame: CGRect) method, so I don't have to write a whole new initializer just to set the background color.
Here is my convenience initializer method (what I'm currently using which works):

convenience init(rect: CGRect){
        self.init(frame: rect)
        self.backgroundColor = UIColor.clearColor()
}

and I call that method in the delegate like this:

var mainFrame = self.window!.bounds
var mainView = HypnosisView(rect: mainFrame)

Let me know if you have any questions. Thanks!


Solution

  • As discussed in the comments, when wanting to customize the behavior of a UIView, it's often easier to use a convenience initializer as opposed to overriding a designated initializer.

    For UIViews specifically, if you override the designated init(frame aRect: CGRect), you are unfortunately also required to override init(coder decoder: NSCoder!) which is part of the NSCoding protocol. So generally if you just want to set a few properties to some default values, do as the original poster asked and create a convenience initializer that in turn calls init(frame aRect: CGRect):

    convenience init(rect: CGRect, bgColor: UIColor){
        self.init(frame: rect)
        self.backgroundColor = bgColor
    }
    

    For a discussion on getting rid of NSCoding compliance, see Class does not implement its superclass's required members