animationUIButton状态更改

我正在使用UIButton的正常和突出显示状态的图像。 他们按预期工作,但我想有一些衰落/合并过渡,而不是只是一个突然的交换。

我怎样才能做到这一点?

这可以使用UIView的过渡animation完成。

Swift 3

UIView.transition(with: button, duration: 4.0, options: .transitionCrossDissolve, animations: { button.isHighlighted = true }, completion: nil) 

Objective-C的

 [UIView transitionWithView:button duration:4.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ button.highlighted = YES; } completion:nil]; 

为了做到这一点,我扩展了UIButton。 用下面的代码添加一个名为hilightedImage的新属性:

 - (void)setHilightImage:(UIImageView *)_hilightImage { if (hilightImage != _hilightImage) { [hilightImage release]; hilightImage = [_hilightImage retain]; } [hilightImage setAlpha:0]; [self addSubview:hilightImage]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.14]; if(hilightImage){ [hilightImage setAlpha:1]; } [UIView commitAnimations]; [super touchesBegan:touches withEvent:event]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { self.highlighted = FALSE; [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.14]; if(hilightImage){ [hilightImage setAlpha:0]; } [UIView commitAnimations]; [super touchesEnded:touches withEvent:event]; } 

@marián-Černý 斯威夫特答案:

 UIView.transitionWithView(button, duration: 4.0, options: .TransitionCrossDissolve, animations: { button.highlighted = true }, completion: nil) 

UIButtonUIViewinheritance

那么你得到它的视图,并调用beginAnimations:context:

然后从那里所有适当的setAnimation方法。

UIView类的以下属性是可以animation的:

  • @属性框架
  • @属性界限
  • @属性中心
  • @属性转换
  • @属性阿尔法
  • @属性backgroundColor
  • @property contentStretch

参考: UIView类参考

这是一个独立的解决scheme,也支持布尔animated标志。

 - (void)setEnabled:(BOOL)enabled animated:(BOOL)animated { if (_button.enabled == enabled) { return; } void (^transitionBlock)(void) = ^void(void) { _button.enabled = enabled; }; if (animated) { [UIView transitionWithView:_button duration:0.15 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ transitionBlock(); } completion:nil]; } else { transitionBlock(); } }