gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:52:41 25 4
gpt4 key购买 nike

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)")
}

}

结果:

View has loaded
View will appear
SubViews will layout
SubViews has layouted
SubViews will layout
SubViews has layouted
View has appeared

如您所见,我已经创建了一个新项目并键入了一些简单的代码。
我没有更改 viewController View 的大小。
为什么“SubViews has layouted”和“SubViews will layout”控制台两次?

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

最佳答案

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

关于ios - 为什么 viewDidLayoutSubviews 和 viewWillLayoutSubviews 被调用了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49279687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com