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

zou*_*oul 3 cocoa-touch core-animation uibutton

我想创造一个UIButton"呼吸",将其alpha值从1.0改为0.7然后再重新开始.代码非常简单,但是当动画运行时,按钮不可点击.对于一个按钮,这是一个遗憾.我可以理解为什么当动画改变它的位置时按钮可能无法点击,但改变alpha对我来说似乎是无害的.有没有办法让按钮可以点击,保持动画而不是手动动画?

Jul*_*ian 10

使用不透明度.

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"];
Run Code Online (Sandbox Code Playgroud)

  • 要停止动画,请调用`[btnTest.layer removeAnimationForKey:@"fadeInOut"];`.要停止视图上的所有动画,请使用`[btnTest.layer removeAllAnimations];`. (2认同)