我会推荐使用核心动画。尝试这样的事情:
-(void) flash{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
if( emergency ){
// Start flashing
[UIView setAnimationRepeatCount:1000];
[UIView setAnimationRepeatAutoreverses:YES];
[btn setAlpha:0.0f];
}else{
// Stop flashing
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationRepeatCount:1];
[btn setAlpha:1.0f];
}
emergency = !emergency;
[UIView commitAnimations];
}
其中 btn 被声明为
@property(nonatomic, retain) IBOutlet UIButton *btn;
紧急情况是一个简单的 BOOL 变量。
调用 flash 开始和停止动画。
在此示例中,为简单起见,我们为 alpha 属性设置动画,但您可以对按钮背景颜色执行相同操作,正如 Sam 在他的回答中所说,或者您喜欢的任何属性。
希望能帮助到你。
更新:
关于在两个图像之间进行转换,请尝试调用imageFlash
而不是flash
:
-(void) imageFlash{
CABasicAnimation *imageAnimation = [CABasicAnimation animationWithKeyPath:@"contents"];
[btn setImage:normalState forState:UIControlStateNormal];
if( emergency ){
imageAnimation.duration = 0.5f;
imageAnimation.repeatCount = 1000;
}else{
imageAnimation.repeatCount = 1;
}
imageAnimation.fromValue = (id)normalState.CGImage;
imageAnimation.toValue = (id)emergencyState.CGImage;
[btn.imageView.layer addAnimation:imageAnimation forKey:@"animateContents"];
[btn setImage:normalState forState:UIControlStateNormal]; // Depending on what image you want after the animation.
emergency = !emergency;
}
您要使用的图像在哪里normalState
以及在哪里:emergencyState
声明为:
UIImage *normalState;
UIImage *emergencyState;
分配图像:
normalState = [UIImage imageNamed:@"normal.png"];
emergencyState = [UIImage imageNamed:@"alert.png"];
祝你好运!