ios - UIKit 布局子视图,即使它没有被要求
问题描述
我在 UIViewControllers 中弄乱了 layoutSubviews 方法。我假设当您在视图上覆盖 layoutSubviews 时,它不会布局其子视图,但事实并非如此,视图及其子视图已正确布局。
class Vieww: UIView {
override func didMoveToSuperview() {
super.didMoveToSuperview()
let centered = UIView()
addSubview(centered)
centered.translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .green
centered.backgroundColor = .red
centered.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1/2).isActive = true
centered.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 1/2).isActive = true
centered.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
centered.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
override func layoutSubviews() {
print("layoutSubviews")
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.layout(Vieww()).center().leading(20).trailing(20).height(400)
}
}
我预计因为我没有调用 layoutSubviews,所以我的视图不会被布置,但我得到的布局就像我确实覆盖了这个方法一样。
解决方案
阅读文档:https ://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews
“默认实现使用您设置的任何约束来确定任何子视图的大小和位置。子类可以根据需要覆盖此方法以执行其子视图的更精确布局。”
推荐阅读
- node.js - Discord.js 机器人提到语音通道
- numbers - 谁能帮我解决这个类比?
- pdf - 在管理员订单 prestashop 1.7.7 中显示我的自定义 pdf
- c - 如何在 C 中验证和解析日期?
- android - 如何使 JetpackCompose DropDownMenu 弹出项目更宽?
- docker - Docker-compose 卷在 raid
- javascript - 如何在反应中从异步函数中检索值?
- python - 为什么python在导入numpy时会调用builtins.compile?
- reactjs - 如何使用 Redux 限制字段中的字符数?
- javascript - 无法在反应JS中访问数组的属性