【发布时间】:2019-12-19 03:39:18
【问题描述】:
我有一个这样定义的自定义子视图:
class CustomSubview:UIView {
let contentView = ContentView(frame: .zero) //ContentView is another custom subview
override init(frame: CGRect) {
super.init(frame: frame)
setupContentView()
}
private func setupContentView() {
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.backgroundColor = UIColor.clear
addSubview(contentView)
contentView.leftAnchor.constraint(equalTo: leftAnchor, constant:10).isActive = true
contentView.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true
contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
contentView.clipsToBounds = true
contentView.isUserInteractionEnabled = true
contentView.layoutIfNeeded()
NSLog("Contentview frame \(contentView.frame)")
}
}
问题是即使在调用 layoutIfNeeded 之后,框架仍然是 CGRect.zero。这是为什么?如何确保立即更新边界?
【问题讨论】:
-
在
contentView上调用layoutIfNeeded()不会改变其大小,因为它会布置其 子视图。一旦其 superview(您在此示例中显示的类)在其自己的layoutSubviews方法中执行布局更新,此视图的框架应该是正确的。 -
那么我需要怎么做才能立即更新框架?
-
我会手动设置它并离开
translatesAutoresizingMaskIntoConstraints但是我同时也怀疑我真的需要在视图初始化时知道框架......如果你想确保位置和大小是正确的,你必须这样做之后layoutSubviews -
正确。不过要小心,因为它可能会被多次调用。
-
contentView.layoutIfNeeded()否。不要在viewDidLoad中进行布局。自动布局约束的全部意义在于,当布局发生在事物的自然过程中时,它们将被遵守。不要试图颠覆它。
标签: ios swift uiview autolayout ios-autolayout