简体   繁体   中英

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 ie 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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM