Edward Huynh
Edward Huynh

Reputation: 2917

UIView's designated initializers in swift

So I've subclassed UIView like so

class CustomView: UIView {
}

And I could do something like

let customView = CustomView()

But when I override what I believe are the two designated initialisers for UIView i.e. init(frame:) and init(coder:) like so

class CustomView: UIView {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.backgroundColor = UIColor.redColor()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.redColor()
    }
}

I can no longer create the view like so as it complains that init() no longer exists

let customView = CustomView()

My understanding is that If I override all the designated initialisers, I should inherit all the convenience initializers as well.

So my question is. Is init() not a convenience initializer on UIView? Or is there another designated initializer on UIView that I haven't overrided yet?

Upvotes: 8

Views: 3777

Answers (1)

matt
matt

Reputation: 534893

init is not a convenience initializer on UIView. init is not an initializer on UIView at all! It is an initializer on its superclass NSObject - UIView merely inherits it. And it is a designated initializer on NSObject. So when you implemented a designated initializer, you cut off inheritance of designated initializers - including init.

Upvotes: 7

Related Questions