为什么viewDidLayoutSubviews和viewWillLayoutSubviews被调用两次?

时间:2018-03-14 13:58:46

标签: ios swift

import UIKit

class ViewController: UIViewController {

    // MARK: -property
//    lazy var testBtn: UIButton! = {
//        var btn: UIButton = UIButton()
//        btn.backgroundColor = UIColor.red
//        print("testBtn lazy")
//        return btn
//    }()

    // MARK: -life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
       print("View has loaded")
        // set the superView backgroudColor
//        self.view.backgroundColor = UIColor.blue
        // add testBtn to the superView
//        self.view.addSubview(self.testBtn)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       print("View will appear")
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
       print("View has appeared")
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
       print("View will disappear")
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
       print("View has desappeared")
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
       print("SubViews will layout")
        // layout subViews
//        'CGRectMake' is unavailable in Swift
//        self.testBtn.frame = CGRectMake(100, 100, 100, 100)
//        self.testBtn.frame = CGRect(x: 100, y: 100, width: 100, height: 100) // CGFloat, Double, Int
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
       print("SubViews has layouted")
//        let testBtn_Width = self.testBtn.frame.width
//       print("testBtn's width is \(testBtn_Width)")
    }

}

结果:

  

查看已加载
  视图将出现
  子视图将布局
  SubViews已经铺设了   子视图将布局
  SubViews已经铺设了   视图已经出现

如您所见,我创建了一个新项目并输入了一些简单的代码 我没有改变viewController视图的大小 为什么“SubViews已经布局”和“SubViews将布局”控制台两次?

为什么viewDidLayoutSubviews和viewWillLayoutSubviews被调用两次?

1 个答案:

答案 0 :(得分:0)

因为在内部调用setNeedsLayoutsetNeedsDisplayInRect时,在任何给定视图上也会调用LayoutSubviews(每个运行循环一次)。例如,如果视图已添加,滚动,调整大小,重复使用等,则适用。