iOS ViewController 生命周期最佳实践

标签 ios xcode 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/

相关文章:

swift - 无法在 View Controller 中引用 Collection View 单元格导出

ios - UITableViewCell 不尊重 shouldIndentWhileEditing = NO?

ios - FB IOS SDK是否提供检查访问 token 有效性的方法?

ios - ios中图片的 ScrollView

c++ - Xcode 项目源文件自动复制

xcode - 在 Xcode 项目中添加图像时出现黑色背景

ios - 如何使用平移手势识别器更改不同 View 的布局约束?

iphone - 如何从委托(delegate)访问 UITableView?

ios - 我如何在核心数据中获得 SUM

objective-c - 获取 xcode 4.5 以警告新的 API 调用