Rob
Rob

Reputation: 4224

Button not correctly located with autolayout after updating constraints

I'm stuck with a strange bug with Auto Layout.

I have two buttons (confirm and delete) side by side, in the same view, each taking a width that's 50% of their superview, and in some situations (when test = true), I want to hide confirm button so delete button takes all the width of the screen.

Here is my autolayout:

enter image description here

Confirm button:

enter image description here

Delete button:

enter image description here

Proportional width is 50% (1:2) of the superview. Now here is my call, happening in viewWillAppear:

if test {
    self.confirmButtonWidthConstraint.constant = 0
    self.deleteButtonWidthConstraint.constant = (self.deleteButton.superview?.frame.width)!
}

However, after doing so here is the result:

enter image description here

And after checking the UI debugger, I can see that oddly, this delete button now has a width of... 480, with a starting x of -160. So I don't really know what's happening here. Please help!

enter image description here

Upvotes: 0

Views: 56

Answers (2)

caseynolan
caseynolan

Reputation: 1246

May I suggest a different tactic?

Embed your buttons in a stack view (UIStackView) with the buttons set to fill equally.

You can then set your button to disappear with button.isHidden = true. The stack view will handle the layout for you gracefully.

Upvotes: 3

beyowulf
beyowulf

Reputation: 15321

You've set the width proportionally but are updating the constraints constant property. This will need lead to the result you desire as the proportional width will simply add the constant value to the multiplier result.

Instead you should set the multiplier property of your constraints. For example:

if test {
    self.confirmButtonWidthConstraint.multiplier = 0.0
    self.deleteButtonWidthConstraint.multiplier = 1.0
}

Upvotes: 2

Related Questions