Snacks
Snacks

Reputation: 513

How to properly animate UIButton between states?

I wanted to make a slow dissolve animation between the Default and Highlighted UIButton state. Pressing the button performs a segue, and takes us to another ViewController. I have managed to do the animation by writing a subclass of UIButton with a single method:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [UIView transitionWithView:self
                      duration:0.15
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{ self.highlighted = YES; }
                    completion:nil];

    [super touchesBegan:touches withEvent:event];
}

And then writing this in the prepareForSegue method of the main ViewController:

if ([sender isKindOfClass:[UIButton class]]) {
        UIButton* button = (UIButton*)sender;
        [UIView transitionWithView:button
                          duration:0.15
                           options:UIViewAnimationOptionTransitionCrossDissolve
                        animations:^{ button.highlighted = NO; }
                        completion:nil];
    }

This works well, but dividing the execution of a single animation into two files does not seem to be the best idea. Is there a better way of doing this?

P.S. using the second part of code in touchesEnded does not work :(

Upvotes: 1

Views: 493

Answers (1)

Artal
Artal

Reputation: 9143

Instead of using touchesBegan and touchesEnded you can try to perform the highlighting in the control events of the button.

In your UIButton subclass:

[self addTarget:self action:@selector(onTouchDown) forControlEvents:(UIControlEventTouchDown | UIControlEventTouchDragEnter)];
[self addTarget:self action:@selector(onTouchUp) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchDragExit | UIControlEventTouchCancel)];

The event methods:

-(void)onTouchDown
{
    //perform your dissolve animation here
}

-(void)onTouchUp
{
    //remove your dissolve animation here
}

Upvotes: 2

Related Questions