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

does loadView get called even if we don't override it in viewcontroller like the other ViewController lifecycle methods?

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

是的,它仍然会被调用。您将观察到与将其添加到视图控制器相同的行为。

override func loadView() {
  // Only call this to observe this is being called.
  // If you want to write your own implementation, you shouldn't call super.loadView().
  // Instead, create your own UIView instance and set self.view = yourView.
  super.loadView() 
}

它总是被调用。来自 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 创建视图控制器时,您才会覆盖它。在此方法中,您将分配 self.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作为你的视图(大概)。

默认情况下,视图只是一个普通的 UIView。如果这就是您所需要的,则根本没有理由调用此方法。 viewDidLoad() 仍然是进行任何额外初始化的完美位置。

有几件事要记住:

  1. 仅分配给您在 loadView() 中的视图。不要调用它(在 右手边;不要调用它的 getter),因为这会导致 无限循环。如果 view 为 nil,则调用 loadView 来创建 它。
  2. 不要打电话给 super.loadView()。此方法旨在为您的视图分配一个视图 属性。通过调用 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.

view 为 nil 时在 loadView() 中创建和赋值。如果你在 loadView 本身内这样做,你将提示 loadView 在它自己的体内被调用。