11
votes

Swift (1.0) inheritance is driving me nuts beyond believe. I can believe have have to ask something that as simple as this but I can't figure it out. I have my custom view which I want to be able create programmatically with init(frame: CGRect) as well as load it from story board in which case init(coder aDecoder: NSCoder) should be used for initialization. in both cases I want to call my custom setup method. Like so :

import UIKit

class CustomView: UIView {

    override convenience init(frame: CGRect) {
        super.init(frame: frame)
        self.myCustomSetup()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.myCustomSetup()
    }

    func myCustomSetup() {
        self.backgroundColor = UIColor.redColor()
    }
}

this does not seem to work, from swift documentation I understand there should only be one designated initializer for class which all the convenience initializers call. In UIView case this should be init(coder aDecoder: NSCoder). I however can not create aDecoder: NSCoder in init(frame: CGRect) neither can I pass nil as its not optional. What should I do ? How can I override them both ?

1
initWithFrame: is also a designated initializer.Leo Natan
Yep that works, thank so you. Convenience keyword was suggested by Xcode :-( Ok what I don't understand is. From documentation there should only be one designated initialiser per class. All the other initialises should call that one. How come I can initialise my class(and UIView) with two separate ones. Separate in sense one does not call the other designated one ? What am I getting wrong ?stringCode
Are you sure about that? Doesn't sound right to me. Perhaps, as a guideline, you should strive to have a little designated initializers as possible, but it makes no sense to limit to one. initWithFrame: and initWithCoder: are as different as can be.Leo Natan
Thank you very much I appear to have been wrong about that.stringCode

1 Answers

6
votes

A class must have at least one designated initializer. It may have more than one.

All you have to do to make your code work is remove the keyword convenience from init(frame: CGRect).