4

I have two buttons on a view controller. They are equal in height and width and spaced nicely, centered on the screen. The problem is that in some circumstances, one of the buttons is hidden. When one of the buttons is hidden, I want the other button to be centered.

For the life of me I haven't been able to figure out how to configure the constraints to get this to happen.

I am able to move the visible button so that it is centered if the other button is hidden, but can only seem to do this after the view is loaded, which makes the button "jump" and looks silly.

  • 1
    You might be able to achieve this effect by using `UIStackView`. Add both buttons to the stack view and center the stack view. – dalton_c Nov 16 '16 at 21:36

3 Answers3

11

Embed both buttons within a UIStackView:

and adjust its settings to your needs:

enter image description here


Result with button1 hidden == false (un-ticked):

Button1 hidden == false (un-ticked)

Result with button1 hidden == true (ticked):

Button1 hidden == true (ticked

shallowThought
  • 19,212
  • 9
  • 65
  • 112
  • 1
    Thank you so much. Not only does this perfectly solve my problem, but it got me to (finally) learn WTH a UIStackView does. – David Vincent Gagne Nov 17 '16 at 21:30
  • Only available in iOS 9+ though. – bagage Sep 29 '17 at 12:45
  • I have one question about this... how we can center the button but it should not take up full space? Also, I'm changing button text on runtime so I want it should only take space of text + some padding. Anyone knows any fix? – Rahul Vyas May 12 '22 at 09:04
0

If you're able to get the button in the right position, try animating it to give it a nice effect. Note this only animates changes in constraints, so if you're doing something else to make the button move it might not work.

UIView.animate(withDuration: 0.5, animations: {
      //do whatever you're doing to make the button 'jump' to the right position here
      self.view.layoutIfNeeded()
})
Frankie
  • 11,508
  • 5
  • 53
  • 60
  • Using this approach, you would need to programmatically reset all of the constraints. Else, the new positions you set will get overwritten by layoutIfneeded, which will move the objects back to the position defined by their constraints. It's the more proper way to do things, to be honest. But a little harder to do. – Jake T. Nov 16 '16 at 21:52
0

Storyboard constraints like this aren't meant to move, and you can cause a lot of UI problems by not doing this properly.

My recommendation? It's not ideal, but just add a third button. If you have to hide the one button, just hide both, and display the third.

Jake T.
  • 4,308
  • 2
  • 20
  • 48