如何在布局子视图后更新约束?

时间:2014-09-16 12:50:34

标签: ios nslayoutconstraint layoutsubviews ios-autolayout

我知道渲染视图按此顺序包含以下3个步骤:

  1. 更新约束
  2. 布局视图(这是我们计算的地方 框架)
  3. 显示
  4. 现在我的问题是,如果我修改自定义按钮高度,并且该按钮具有周围视图的约束,我如何更新该约束并避免与视图重叠?你可以看到评论的行,不是它们的作用。

    class DynamicHeightButton: UIButton {
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            let size = (self.titleForState(UIControlState.Normal)! as NSString).boundingRectWithSize(CGSizeMake(self.bounds.size.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(17)], context: nil)
            self.bounds.size.height = size.height + 8
    
            //viewController!.view.setNeedsUpdateConstraints()
            //self.setNeedsUpdateConstraints()
            //self.setNeedsLayout()
        }
    }
    

1 个答案:

答案 0 :(得分:1)

使用Autolayout视图时,不应设置框架。而不是它应该调整约束,通常是常数'属性。

在我的情况下,我正在改变视图的高度,并在此过程中破坏约束。

我在自定义类中添加了3行:

@IBOutlet weak var height: NSLayoutConstraint

self.bounds.size.height = size.height + 8
height.constant = size.height + 8
相关问题