user5741640
user5741640

Reputation:

Replacing UIView's self with another instance in Swift

I want to initialize xib-files programmatically in Swift, so I created the class MyView.

The initialization of the xib is declared in the setup() method, where loadNibNamed() is called. This returns an additional view, which I have to add as a subview to my current/initial view.

I saw in User Interface Inspector that behind MyView is the initial view, which has of course also own properties. I do not like this behaviour and do not want to modify properties twice. In the end I want to achieve that the instance from the initializer would be replaceable with the instance that has been created by the call of loadNibNamed(); figurative something like self = view.

I added the code of the initializers and the setup() method.

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

init(in frame: CGRect) {
    NSLog("init with CGRect")
    super.init(frame: frame)
    setup()
}


private func setup() {
    NSLog("setting up")
    let view = Bundle.main.loadNibNamed("MyView", owner: self, options: nil)!.first as! MyView
    addSubview(view)
}

Upvotes: 1

Views: 1075

Answers (1)

matt
matt

Reputation: 535945

You cannot substitute one self for another in an initializer. init and nib-loading are related, but the relationship runs the opposite way from your proposal: loading the view from the nib will call your init(coder:).

What you need is not an initializer but a factory.

Give MyView a class method (class func) that a client can call to load the nib and return the instance.

class func new() -> MyView {
    let view = Bundle.main.loadNibNamed("MyView", owner: nil, options: nil)!.first as! MyView
    return view
}

Usage:

let v = MyView.new()

Upvotes: 2

Related Questions