简体   繁体   English

如何以编程方式正确初始化 ViewController? loadView() vs init(nibName: nil, bundle: nil)

[英]How to properly initialize ViewController programmatically? loadView() vs init(nibName: nil, bundle: nil)

I'd was wondering what is a proper way of initializing a ViewController from code.我想知道从代码初始化 ViewController 的正确方法是什么。 No xib or storyboards.没有xib或故事板。

I know two ways.我知道两种方法。 Overriding loadView()覆盖loadView()

override func loadView() {
    view = UIView()
    commonInit() // some init
}

Or providing init()或者提供init()

init() {
    super.init(nibName: nil, bundle: nil)
    commonInit() // some init
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

If we provide the init and the nib is nil I know we call a default implementation of loadView() which sets our view property.如果我们提供 init 并且 nib 为零,我知道我们调用了 loadView() 的默认实现,它设置了我们的视图属性。

Which is a more correct way and why?哪个是更正确的方法,为什么?

Separation of concern would advice to use both methods.关注点分离建议同时使用这两种方法。 Override loadView() to init and setup the view, init() to initialise other properties.覆盖loadView()以初始化并设置视图,覆盖init()以初始化其他属性。

loadView() is ran lazily, meaning that it won't be called until something tries to access the .view property of the view controller. loadView()是惰性运行的,这意味着它不会被调用,直到有人尝试访问视图控制器的.view属性。

To expand on what init should contain, if your view controller needs network access, it's the place where you should fetch (or inject) your HTTP manager for example.为了扩展 init 应该包含的内容,如果您的视图控制器需要网络访问,例如您应该获取(或注入)您的 HTTP 管理器的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM