Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

iphone - Fading out an UIButton when touched

I've got a Selected-state and a Normal-state for an UIButton that both are UIImages. When a button is touched, I'd like it to hit the selected-state and then animate back to the normal-state over the period of one second. I've set the following animation when the UIButton* btn is pressed, but it just switches right back to deselected state again. How should I go about achieving this?

[btn setSelected:YES];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0f];
[btn setSelected:NO];
[UIView commitAnimations];

Cheers

Nik

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since selected is not an animatable property, that won't work (as you've found out). My solution would be to have the selected state of the btn be in a separate UIImageView directly below the button in the exact same location. Then in the action for tapping the button:

- (void) tapButton:(UIButton *)btn {
    btn.alpha = 0;
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1];
    [UIView setAnimationDelegate:[UIApplication sharedApplication]];
    [UIView setAnimationDidStopSelector:@selector(endIgnoringInteractionEvents)];
    btn.alpha = 1;
    [UIView commitAnimations];
}

Note I also added the begin/endIgnoringInteractionEvents calls so the user can't tap on the button while it's fading back to its normal state. If you want to allow that, replace the begin/end calls with [UIView setAnimationBeginsFromCurrentState];


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...