【问题标题】:Autolayout frame update in viewDidLoadviewDidLoad 中的自动布局框架更新
【发布时间】: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


【解决方案1】:

改变你的

contentView.layoutIfNeeded()

contentView.setNeedsLayout()
layoutIfNeeded()

您需要告诉CustomSubview 对象重新布置自己,而不仅仅是contentView

【讨论】:

    【解决方案2】:

    CustomSubview 类中,实现:

    override func layoutSubviews() {
        super.layoutSubviews()
        NSLog("In layoutSubviews() - Contentview frame \(contentView.frame)")
    }
    

    这就是你拥有实际框架的地方。请注意,只要您的 CustomSubview 实例发生更改,例如设备旋转(假设您已将其设置为在其父视图更改大小时更改大小),它就会被调用。

    因此,您需要计算要显示多少“缩略图”,并根据需要添加或删除它们。

    【讨论】:

      猜你喜欢
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多