Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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     } } 
like image 536
Gralex Avatar asked Feb 07 '15 16:02

Gralex


People also ask

How do I add Xib in Objective C?

Input the cocoa touch class name, select it's superclass, and check the Also create XIB file checkbox, select the coding language that you use ( Swift or Objective-C), then click Next button. Select the xib file saved location in the next popup dialog, then click Create button to create them.


1 Answers

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 func awakeFromNib() {     super.awakeFromNib()      print(aButt) } 
like image 96
fz. Avatar answered Sep 30 '22 08:09

fz.