问题描述
我有一个 UIButton 的 Selected 状态和一个 Normal 状态,它们都是 UIImages.当一个按钮被触摸时,我希望它达到选定状态,然后在一秒钟内动画回到正常状态.当按下 UIButton* btn 时,我设置了以下动画,但它只是再次切换回取消选择状态.我应该如何实现这一目标?
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];
干杯
尼克
推荐答案
因为 selected
不是动画属性,所以它不起作用(正如你所发现的).我的解决方案是让 btn 的选定状态位于按钮正下方完全相同位置的单独 UIImageView 中.然后在点击按钮的动作中:
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];
}
请注意,我还添加了 begin/endIgnoringInteractionEvents
调用,因此用户无法在按钮逐渐恢复正常状态时点击该按钮.如果您想允许这样做,请将 begin/end
调用替换为 [UIView setAnimationBeginsFromCurrentState];
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];
这篇关于触摸时淡出 UIButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!