Animate UIButton state change
I'm using a UIButton with images for normal and highlighted states. They work as expected but I want to have some fading/merging transition and not just a sudden swap.
How can I do that?
This can be done using transition animation of a UIView. It does not matter the isHighlighted
property is not animatable, because it transitions the whole view.
Swift 3
UIView.transition(with: button,
duration: 4.0,
options: .transitionCrossDissolve,
animations: { button.isHighlighted = true },
completion: nil)
Objective-C
[UIView transitionWithView:button
duration:4.0
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{ button.highlighted = YES; }
completion:nil];
To accomplish that I extended UIButton. added a new property called hilightedImage with the following code:
- (void)setHilightImage:(UIImageView *)_hilightImage
{
if (hilightImage != _hilightImage) {
[hilightImage release];
hilightImage = [_hilightImage retain];
}
[hilightImage setAlpha:0];
[self addSubview:hilightImage];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.14];
if(hilightImage){
[hilightImage setAlpha:1];
}
[UIView commitAnimations];
[super touchesBegan:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
self.highlighted = FALSE;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.14];
if(hilightImage){
[hilightImage setAlpha:0];
}
[UIView commitAnimations];
[super touchesEnded:touches withEvent:event];
}
UIButton
inherits from UIView
So then you get its view and call beginAnimations:context:
Then all the appropriate setAnimation methods from there.
The following properties of the UIView
class are animatable:
- @property frame
- @property bounds
- @property center
- @property transform
- @property alpha
- @property backgroundColor
- @property contentStretch
Ref: UIView Class Reference