Dave123
Dave123

Reputation: 316

How to replace button with an animation in Xcode

I have a UIButton in my code that moves steadily across the screen. Currently, when the user presses the button, the alpha changes to 0 and it just disappears. What I'd like to do is run a separate animation after the button is pressed/it has disappeared. Seems easy enough but the catch is I need to run the animation at the exact point of the button when it is pressed. And I'm drawing a blank on how to make this happen. Any help will be much appreciated! I'll post some relevant code below.

-(void)movingbuttons{
    movingButton2.center = CGPointMake(x, y);
    displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(moveObject)];
    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}

-(void)moveObject{
    movingButton2.center = CGPointMake(movingButton2.center.x , movingButton2.center.y +1);
}


-(IBAction)button2:(id)sender {
    [UIView beginAnimations:nil context:NULL];
    [movingButton2 setAlpha:0];
    [UIView commitAnimations];

}

Upvotes: 0

Views: 530

Answers (2)

Ushan87
Ushan87

Reputation: 1623

Replace your button2 action with below code and implement the someOtherMethodWithAnimation method with the animation you want :)

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
 movingButton2.alpha = 0;
[UIView commitAnimations];
[self performSelector:@selector(someOtherMethodWithAnimation) withObject:nil afterDelay:1.0];

Upvotes: 1

Mike D
Mike D

Reputation: 4946

Replace your animation with:

[UIView animateWithDuration:0.25
             animations:^{
                 self.movingbutton2.alpha = 0.0;
                             // modify other animatable view properties here, ex:
                             self.someOtherView.alpha = 1.0;
             }
             completion:nil];

Just a nit picking point, but is the button in your view controller's .xib file correctly hooked up to your IBOutlets and IBActions?

UPDATE:

You are not limited to modifying that one button in your method. You add what ever code you want in the animation block (see the udated axample above).

UIView animatable properties, there is an animation section there.

Another approach could be (I am just using alpha as an example):

[UIView animateWithDuration:1.0
                 animations:^{
                     self.movingButton2.alpha = 0.0;
                 }
                 completion:^{
                     [UIView animatateWithDuration:0.25
                                        animations:^{
                                            self.someOtherView.alpha = 1.0;
                                        }
                                       completion:nil];
  }];

This will more likely guarantee the animations will hapen one after another.

Upvotes: 0

Related Questions