Sk0prion Sk0prion - 9 days ago 4
iOS Question

IBOutlet properties nil after custom view loaded from xib

Something strange going on with IBOutlets.
enter image description here

In code I've try to access to this properties, but they are

nil
. Code:

class CustomKeyboard: UIView {

@IBOutlet var aButt: UIButton!
@IBOutlet var oButt: UIButton!

class func keyboard() -> UIView {
let nib = UINib(nibName: "CustomKeyboard", bundle: nil)
return nib.instantiateWithOwner(self, options: nil).first as UIView
}

override init() {
super.init()
commonInit()
}

override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}

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

// MARK: - Private
private func commonInit() {
println(aButt)
// aButt is nil

aButt = self.viewWithTag(1) as UIButton
println(aButt)
// aButt is not nil
}
}

fz. fz.
Answer

That's expected, because the IBOutlet(s) are not assigned by the time the initializer is called. You don't need the commonInit, just an override of awakeFromNib as follows:

override awakeFromNib() {
    super.awakeFromNib()

    println(aButt)
}