0

In Xcode, when using auto layout, I wanted to position a button so that if this button doesn't have sibling button then it should align X center, otherwise both can sit side by side.

I have tried with yellow.leadingSpace to superview >= 20, yellow.alignX to superview, but it is not working, yellow button always stays on the left.

enter image description here

1
  • You can add this in stack view Commented Feb 26, 2019 at 8:15

1 Answer 1

5

as Uma already suggested you can use a UIStackView for this. Simply add both buttons to the UIStackView and set the spacing. You also could do it without a UIStackView with a combination of constraints:

  1. Add a horizontal center constraint to the first button.
  2. Change the priority of this constraint to 750.
  3. Add a spacing constraint between the buttons.
  4. When second button gets hidden you need to disable the spacing constraint by buttonPaddingConstraint.isActive = false.
  5. If you show the second button again you need to re-add the spacing constraint by: leftButton.leadingAnchor.constraint(equalTo: rightButton.trailingAnchor, constant: 20).isActive = true

If you want to animate hiding one of the buttons the outcome depends method to use. If you are going to use a UIStackView have a look at "First Button" and "Second Button" in the following image. If you are going without a UIStackView have a look at "Third Button" and "Fourth Button". autolayout

I uploaded the xcode project containing both options here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.