首先,文档没有说您需要调用super. 将其与 eg 进行对比viewWillAppear(_:),其文档指出:
如果您覆盖此方法,则必须super在您的实现中的某个时间点调用。
因此,super只有当您有一个自定义子类时才需要调用UIViewController,让我们调用它BaseViewController,它在viewDidLoad().
当你再继承自时BaseViewController,你可能需要调用super来做BaseViewController. 根据它的性质,您需要在子类的开头、中间某处或结尾处执行此操作viewDidLoad()。这取决于BaseViewController正确记录它。
这是一个人为的例子:
class ColorfulViewController: UIViewController {
/// Defines background color of view. Override in subclass.
var shinyColor: UIColor = .red
/// Sets the background color. Make sure to call `super` in subclass.
func viewDidLoad() {
backgroundColor = shinyColor
}
}
class PinkViewController: ColorfulViewController {
override var shinyColor: UIColor = .systemPink
func viewDidLoad() {
super.viewDidLoad() // This one doesn't matter where it goes.
// Additional work.
}
}
另一个你想super在最后调用的人为示例:
class CountingViewController: UIViewController {
var count: Int = 0
/// Counts the subviews. When subclassing, make sure to call `super` *after*
/// view is fully configured.
func viewDidLoad() {
count = view.subviews.count
}
}
class FooViewController: CountingViewController {
override var shinyColor: UIColor = .systemPink
func viewDidLoad() {
// Additional work.
super.viewDidLoad()
}
}