How to crossfade a button between a selected and unselected state in xcode?
I have two images for a button: one for the normal state, and one for the selected state. When I ch开发者_JAVA百科ange from the selected state back to the normal state, I would like this to happen with a crossfade effect over a couple of seconds.
What I am doing so far is using two UIView animations: the first one goes from an alpha of 1.0 to an alpha of .5 in the selected state. Then I switch to the normal state and perform a second UIView animation going from an alpha of .5 to an alpha of 1.0.
I am not thrilled with the visual effect (abrupt transition from selected to normal image). I also read that UIView should no longer be used. So what is the right approach here? A code sample would be very useful too.
For me this worked:
[UIView transitionWithView: button duration: 4.0 options: UIViewAnimationOptionTransitionCrossDissolve animations: ^{
[button setSelected: !button.isSelected];
} completion: nil];
But this only worked when I set the same UIImage
to UIControlStateHighlighted
and UIControlStateSelected
with those three following calls (leaving one call did not work for me):
[button setImage: img forState: UIControlStateSelected | UIControlStateHighlighted];
[button setImage: img forState: UIControlStateSelected];
[button setImage: img forState: UIControlStateHighlighted];
The following is quite simple and will transition from the selected to not selected state in 4 seconds. The only problem is that the transition doesn't work well when the button is also moving at the same time.
button.selected = TRUE;
CATransition *transition = [CATransition animation];
transition.duration = 4.0;
transition.type = kCATransitionFade;
transition.delegate = self;
[button.layer addAnimation:transition forKey:nil];
button.selected = TRUE;
I finally found what I needed: instead of assigning images to the selected and non-selected states of my button, I keep my button transparent and add instead two views to that button, initially with an alpha of 1.0 and 0.0.
When the button is selected and I enter the method specified in the selector, I use an animation to transition between these two views as follows:
NSArray * subviewArray = [button subviews];
[UIView animateWithDuration:2.0
animations:^ {
((UIView *)[subviewArray objectAtIndex:0]).alpha = 0.0;
((UIView *)[subviewArray objectAtIndex:1]).alpha = 1.0;
}
completion:nil];
This approach also works if the button is moving during the transition. I hope this helps others facing the same question in the future!
精彩评论