我正在使用带有正常和突出显示状态图像的UIButton。它们按预期工作但我希望有一些渐变/合并过渡,而不仅仅是突然交换。
我该怎么做?
答案 0 :(得分:115)
这可以使用UIView的过渡动画来完成。 isHighlighted
属性不可动画无关紧要,因为它会转换整个视图。
UIView.transition(with: button,
duration: 4.0,
options: .transitionCrossDissolve,
animations: { button.isHighlighted = true },
completion: nil)
[UIView transitionWithView:button
duration:4.0
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{ button.highlighted = YES; }
completion:nil];
答案 1 :(得分:3)
为了实现这一点,我扩展了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];
}
答案 2 :(得分:2)
这是一个自包含的解决方案,它还支持布尔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();
}
}
答案 3 :(得分:2)
@marián-Černý以 Swift 回答:
UIView.transitionWithView(button,
duration: 4.0,
options: .TransitionCrossDissolve,
animations: { button.highlighted = true },
completion: nil)
答案 4 :(得分:1)
UIButton
继承自UIView
然后你得到它的观点并致电beginAnimations:context:
然后从那里得到所有合适的setAnimation方法。
UIView
类的以下属性是可动画的:
答案 5 :(得分:0)
使用 CustomButton 而不是 UIButton
并覆盖 isHighlighted
属性对我有用;
class KeypadButton: UIButton {
var highlightDuration: TimeInterval = 0.25
override var isHighlighted: Bool {
didSet {
if oldValue == false && isHighlighted {
highlight()
} else if oldValue == true && !isHighlighted {
unHighlight()
}
}
}
func highlight() {
animateBackground(to: highlightedBackgroundColor, duration: highlightDuration)
}
func unHighlight() {
animateBackground(to: normalBackgroundColor, duration: highlightDuration)
}
private func animateBackground(to color: UIColor?, duration: TimeInterval) {
guard let color = color else { return }
UIView.animate(withDuration: highlightDuration) {
self.backgroundColor = color
}
}
}