iOS中View Controller初始化注意事项(使用nib)

970 阅读1分钟

iOS中View Controller初始化注意事项(使用nib)

本文参考了简书上的题为《使用Nib创建View Controller》的文章

初始化UIController有三种方法:

方法一:

let controller = MyViewController(nibName: "yournib", bundle: nil)

这个方法的特点是,显式地指定nibName

方法二:

let controller = MyViewController()

相当于方法一的nibName传入nil,这种方法要求nib文件与Controller类同名。

  • 如果view controller的class name以Controller结尾,比如NibViewController,那么系统就会匹配不包括Controller的nib文件,即NibView.nib。
  • 系统还会匹配完全同名的nib文件。比如,对于NibViewController,匹配NibViewController.nib。这也是为什么推荐nib文件与view controller同名的原因

此处附上ViewController的部分代码注释

/*
  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 NS_DESIGNATED_INITIALIZER;

方法三:

class MyViewController:UIViewController{
    override var nibName: String? {
        return "yourNibName"
    }
}

重写UIViewController中的nibName之后,同时使用方法一也无法修改nibName。

我个人认为方法三比较好,因为这样比较符合单一职责原则(SRP)。