Slide in an UIButton and push other UIButton when a certain distance is reached

141 views Asked by At

I would like to slide in a UIButton (grey color in screenshot) from the left to right and center it on the screen. There is an UIButton (orange color in screenshot) already though that is centered and this button should be pushed to the right and always have a distance of 20 from the UIButton that slides in.

enter image description here

The centered button (in orange) has four constraints:

  • Height constraint
  • Width constraint
  • Top space to Layout Guide constraint
  • Horizontal constraint

Currently the button that will slide in (in grey) has the following constraints:

  • Center Y relationship to the orange button
  • Height constraint
  • Width constraint
  • Leading space to superview

The idea that I had was to add an outlet to the grey UIButton's "leading space" constraint and to animate that using the UIView's animateWithDuration:animations: method:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.slideInLeadingConstraint.constant = 100;
    [self.slideInButton setNeedsUpdateConstraints];
    [UIView animateWithDuration:3.0 animations:^{
        [self.slideInButton layoutIfNeeded];
        [self.centerButton layoutIfNeeded];
    }];
}

What could I change in the constraint for this to work?

1

There are 1 answers

3
Tim Bodeit On BEST ANSWER
  1. Since you would expect the orange button to move at some point, you can't force it to be centered. Lower the priority from 1000 to something lower. This means: I would really like it to be centered, but it doesn't have to be.

  2. Add a horizontal distance (leading/trailing) constraint between the two buttons. Set its value to >= 20. This means: The distance cannot go under 20pt, but anything larger is fine.

  3. Animate away ;)
    Inside your animation block, you need to call layoutIfNeeded on all views involved in the animation or on one of their common superviews.

Note:
The reason why you had problems with this is that you have called it from viewDidLoad. At that point, the view has been fully initialized, but not added to the hierarchy yet.
It's not yet certain, how big the parent view will be and dimensions for the animation will have to be guessed (by just taking the dimensions of your scene in the storyboard).
Performing the animation after it has been initially displayed (e.g. in viewDidAppear) causes the animation to be calculated with the right dimensions.