xcodeswiftuiviewnibinitwithcoder

Subclass UIView with Swift, use in Nib


I am trying to subclass UIView with Swift and give my class an init with one parameter. The required Init With Coder initializer is tripping me up. I do, in fact, want to be able to plop my view into a Nib file. My understanding is that this will call Init With Coder. Is there any way to have this initializer called with addl. params, other than the decoder? Right now I am assigning default values to my instance variables, as shown below, so that the code will compile.

class ClassName: UIView {

    var dimension: Int = {
        return 5
    }()

}

My initializers are set up as shown below.

init(Int: dimension) {
    self.dimension = dimension
    super.init(frame: CGRectZero)
}

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

Is it true that if you initialize a view via a Nib file, there is no way to pass in any novel parameters?


Solution

  • Views created from a Nib will always be initialized using init(coder:).
    For that reason you must either initialize all your variables immediately with proper values or make them optional.

    var dimension = 0