<分区>
有谁知道深入解释 View Controller 生命周期的好教程。我已经阅读了文档,所以请不要将我链接到它们。我只是在寻找每个函数的实用解释,例如 viewDidLoad 和 viewWillAppear、viewWillLayoutSubviews 等,以及何时最好使用 Swift 中的示例。如果没有教程,任何人都愿意在他们的答案中解释它们。
<分区>
有谁知道深入解释 View Controller 生命周期的好教程。我已经阅读了文档,所以请不要将我链接到它们。我只是在寻找每个函数的实用解释,例如 viewDidLoad 和 viewWillAppear、viewWillLayoutSubviews 等,以及何时最好使用 Swift 中的示例。如果没有教程,任何人都愿意在他们的答案中解释它们。
最佳答案
我使用 swift 为您展示了代码。
import UIKit
class LifeCycleViewController: UIViewController {
// MARK: -property
lazy var testBtn: UIButton! = {
var btn: UIButton = UIButton()
btn.backgroundColor = UIColor.redColor()
return btn
}()
// MARK: -life cycle
override func viewDidLoad() {
super.viewDidLoad()
println("View has loaded")
// set the superView backgroudColor
self.view.backgroundColor = UIColor.blueColor()
// add testBtn to the superView
self.view.addSubview(self.testBtn)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("View will appear")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
println("View has appeared")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
println("View will disappear")
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
println("View has desappeared")
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
println("SubViews will layout")
// layout subViews
self.testBtn.frame = CGRectMake(100, 100, 100, 100)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
println("SubViews has layouted")
var testBtn_Width = self.testBtn.frame.width
println("testBtn's width is \(testBtn_Width)")
}
}
结果如下:
View has loaded
View will appear
SubViews will layout
SubViews has layouted
testBtn's width is 100.0
SubViews will layout
SubViews has layouted
testBtn's width is 100.0
View has appeared
您可以清楚地看到ViewController 的生命周期。
关于iOS ViewController 生命周期最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30514772/