添加约束时更改框架的UIButton

时间:2015-05-30 18:22:08

标签: swift autolayout constraints

我在UITableViewCell中有一个循环UIButton,我正在以编程方式创建。它工作正常,直到我添加一个约束来将其置于其超级视图中。

在我向其添加约束之前,这就是我的按钮的样子:

enter image description here

这就是我添加约束后的样子:

enter image description here

这是我的代码:

var thumbnailBtn = UIButton.buttonWithType(.Custom) as! UIButton

func setupViews() {
    backgroundColor = .colorFromCode(0x3f3f3f)

    thumbnailBtn.frame = CGRectMake(0, 0, 80, 80)
    thumbnailBtn.layer.cornerRadius = 0.5 * thumbnailBtn.bounds.size.width
    thumbnailBtn.backgroundColor = UIColor.greenColor()
    thumbnailBtn.setTitle("Test", forState: UIControlState.Normal)
    thumbnailBtn.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

    contentView.addSubview(menuControlContainerView)
    menuControlContainerView.addSubview(thumbnailBtn)

    updateConstraints()
}

override func updateConstraints() {
    if !didSetupConstraints {
        UIView.autoSetPriority(1000) {
            self.menuControlContainerView.autoSetContentCompressionResistancePriorityForAxis(.Vertical)
        }

        menuControlContainerView.autoPinEdgeToSuperviewEdge(.Top, withInset: 0)
        menuControlContainerView.autoPinEdgeToSuperviewEdge(.Leading, withInset: 0)
        menuControlContainerView.autoPinEdgeToSuperviewEdge(.Trailing, withInset: 0)
        menuControlContainerView.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 0)

        thumbnailBtn.autoCenterInSuperview()

        didSetupConstraints = true
    }

    super.updateConstraints()
}

我注意到,如果我将这行代码[thumbnailBtn.autoSetDimensionsToSize(CGSizeMake(80, 80))]添加到updateConstraints(),它的工作原理如下:

enter image description here

但这是最简洁的方法吗,因为我设置了两次大小?

任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

您可以在初始帧中设置大小,但是稍后开始使用约束来指定位置(和超视图布局)时这是不合适的。实际上你应该创建一个普通视图(使用你正在使用的第三方库中的相应方法)然后使用约束指定大小和位置(你已经尝试过的那些是合适的)。

视图很可能在您居中时调整大小,因为第三方库将自动调整大小掩码转换为约束,这允许约束引擎基本上做任何想要的事情,因为任何设置都满足方程式。

相关问题