[Swift]ViewController中xib控件爲空

在ViewController的xib中定義了一些控件,而後在使用的時候會由於這個控件爲空而崩潰,報錯爲:
Swift Error fatal error: unexpectedly found nil while unwrapping an Optional value

  

 What?swift

解決辦法以下:
 
1.首先要保證正確初始化了ViewController,使用初始化方法 init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)  初始化視圖控制器(OC中對應 -(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil),OC中直接使用init也是能夠的,這時系統會自動調用initWithNibName 方法。
/*
  The designated initializer. If you subclass UIViewController, you must call the super implementation of this
  method, even if you aren't using a NIB.  (As a convenience, the default init method will do this for you,
  and specify nil for both of this methods arguments.) In the specified NIB, the File's Owner proxy should
  have its class set to your view controller subclass, with the view outlet connected to the main view. If you
  invoke this method with a nil nib name, then this class' -loadView method will attempt to load a NIB whose
  name is the same as your view controller's class. If no such NIB in fact exists then you must either call
  -setView: before -view is invoked, or override the -loadView method to set up your views programatically.
*/
- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil

  

2.在viewDidLoad方法加載以前,這些xib的控件是可能爲空的,因此在變量的屬性觀察器中使用xib控件時要注意。如:app

   var naviTitle :String?{
        didSet{
            naviView.title = naviTitle
        }
    }

  應當在viewDidLoad以後使用這些控件。 ide

相關文章
相關標籤/搜索