Cocoa touch 如何使用动画alpha制作可点击的UIButton?

Cocoa touch 如何使用动画alpha制作可点击的UIButton?,cocoa-touch,core-animation,uibutton,Cocoa Touch,Core Animation,Uibutton,我想创建一个“呼吸”的ui按钮,将其alpha值从1.0更改为0.7,然后再次更改,重复。代码非常简单,但当动画运行时,按钮不可单击。对于一个按钮来说,这是一个遗憾。我能理解为什么当动画改变位置时按钮可能无法点击,但改变alpha对我来说似乎是无害的。有没有办法使按钮可点击,保持动画,而不是手动制作动画?使用不透明度 UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btnTest.frame = CGR

我想创建一个“呼吸”的
ui按钮,将其alpha值从1.0更改为0.7,然后再次更改,重复。代码非常简单,但当动画运行时,按钮不可单击。对于一个按钮来说,这是一个遗憾。我能理解为什么当动画改变位置时按钮可能无法点击,但改变alpha对我来说似乎是无害的。有没有办法使按钮可点击,保持动画,而不是手动制作动画?

使用不透明度

UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnTest.frame = CGRectMake(0, 0, 100, 100);
[btnTest setTitle:@"Breathe" forState:UIControlStateNormal];
[btnTest addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnTest];

CABasicAnimation *fadeAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"]; 
fadeAnimation.fromValue=[NSNumber numberWithFloat:0.7];
fadeAnimation.toValue=[NSNumber numberWithFloat:1.0];   
fadeAnimation.duration=1.0;
fadeAnimation.repeatCount=INFINITY;
fadeAnimation.autoreverses=YES;

[btnTest.layer addAnimation:fadeAnimation forKey:@"fadeInOut"];

太好了,这很有效。我以前尝试过为图层设置动画,而不是按钮,但是我在寻找
alpha
属性,却忽略了
不透明度
。无论哪种方式,它都不适用于隐式动画,您必须将动画直接附加到层,按钮才能工作。非常感谢。它就像一个魔术。谢谢,但要停止动画很热?要停止动画,请调用
[btnTest.layer removeAnimationForKey:@“fadeInOut”]。要停止视图上的所有动画,请使用
[btnTest.layer removeAllAnimations]