Thomas
Thomas

Reputation: 2386

UIButton changing frame when constraint added

I have a circular UIButton inside a UITableViewCell that I'm creating programmatically. It works fine, until I add a constraint to center it in it's superview.

This is what my button looks like before I add the constraint to it:

enter image description here

And this is what it looks like after I add the constraint:

enter image description here

Here's my code:

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

I noticed if I add this line of code [ thumbnailBtn.autoSetDimensionsToSize(CGSizeMake(80, 80)) ] to updateConstraints() it works and looks like this:

enter image description here

But is this the cleanest way to do this since I'm setting the size twice?

Any help will greatly be appreciated. Thanks.

Upvotes: 0

Views: 242

Answers (1)

Wain
Wain

Reputation: 119021

You set the size in the initial frame but that is inappropriate when you later start using constraints to specify the position (and the superview layout). Really you should just create a plain view (using the appropriate method from the 3rd party library you're using) and then specify the size and position using constraints (the ones you've already tried are appropriate).

The view is most likely resized when you centre it because the 3rd party library removes the auto-resizing mask conversion to constraints, this allows the constraint engine to basically do whatever it wants as any settings satisfy the equations.

Upvotes: 1

Related Questions