Search code examples
iosswiftautolayout

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


Solution

  • 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.