1

我知道渲染视图按以下顺序执行以下 3 个步骤:

  1. 更新约束
  2. 布局视图(这里是我们计算帧的地方)
  3. 展示

现在我的问题是,如果我修改自定义按钮的高度,并且该按钮与周围的视图有约束,我该如何更新该约束并避免与视图重叠?您可以看到注释行,它们都不起作用。

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()
    }
}
4

1 回答 1

1

不应该设置使用自动布局视图的框架。而不是应该调整约束,通常是“常量”属性。

就我而言,我正在更改视图的高度并在此过程中打破约束。

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

@IBOutlet weak var height: NSLayoutConstraint

self.bounds.size.height = size.height + 8
height.constant = size.height + 8
于 2014-09-16T13:01:54.340 回答