gpt4 book ai didi

ios - 即使我们不像其他 ViewController 生命周期方法那样在 viewcontroller 中覆盖它,是否也会调用 loadView?

转载 作者:行者123 更新时间:2023-12-01 16:01:16 25 4
gpt4 key购买 nike

即使我们不像其他 ViewController 生命周期方法那样在 View Controller 中覆盖它,是否也会调用 loadView?
即使我们不覆盖 ViewDidLoad 方法,我们也知道这个生命周期方法将被 ios 内部调用。 LoadView 也会发生同样的事情吗?还是仅在 VC 中的 View 为 nil 或我们显式覆盖它时才调用它?

最佳答案

它总是被调用。来自 documentation ,

The view controller calls this method when its view property is requested but is currently nil. This method loads or creates a view and assigns it to the view property.

If the view controller has an associated nib file, this method loads the view from the nib file. A view controller has an associated nib file if the nibName property returns a non-nil value, which occurs if the view controller was instantiated from a storyboard, if you explicitly assigned it a nib file using the init(nibName:bundle:) method, or if iOS finds a nib file in the app bundle with a name based on the view controller'€™s class name. If the view controller does not have an associated nib file, this method creates a plain UIView object instead.



...

You can override this method in order to create your views manually. If you choose to do so, assign the root view of your view hierarchy to the view property. The views you create should be unique instances and should not be shared with any other view controller object. Your custom implementation of this method should not call super.



即使您不覆盖它,它也会被调用。通常,只有当您不想从其 nib 创建 View Controller 时,您才会覆盖它。在此方法中,您将分配 self.view一些值(因为 view 被延迟加载)。如果您没有为您的 View 属性分配一些特殊的子类,您通常可以通过将所有逻辑添加到 viewDidLoad() 来获得。 .

这是一个示例实现:
// Say you have some custom view you want use as your controller's view
class CustomView: UIView { ... }

...
// In your view controller, you can set that custom instance to your view property.
override func loadView() {
self.view = CustomView()
}
UITableViewController ,例如,设置 UITableView作为您在此方法中的观点(大概)。

默认情况下, View 只是一个普通的 UIView。如果这就是您所需要的,那么根本没有理由调用此方法。 viewDidLoad()仍然是进行任何额外初始化的绝佳场所。

有几件事要记住:
  • 仅在 loadView() 中分配给您的 View .不要调用它(在
    右侧;不要调用它的getter),因为这会导致
    无限循环。如果 view为零,loadView被调用创建
    它。
  • 请勿调用super.loadView() .此方法旨在将 View 分配给您的 View 属性。通过调用 super,您将执行此操作两次。


  • 有关您可能陷入的无限循环陷阱的更多信息:

    来自 UIViewController 的 view :

    If you access this property and its value is currently nil, the view controller automatically calls the loadView() method and returns the resulting view.


    viewloadView() 中创建和分配当它为零时。如果你在 loadView 内这样做本身,你会提示 loadView在自己的体内被调用。

    关于ios - 即使我们不像其他 ViewController 生命周期方法那样在 viewcontroller 中覆盖它,是否也会调用 loadView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61112180/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com