如何在状态之间正确设置 UIButton 的动画?
How to properly animate UIButton between states?
我想在默认和突出显示的 UIButton 状态之间制作一个缓慢溶解的动画。按下按钮执行 segue,并将我们带到另一个 ViewController。我已经设法通过使用一种方法编写 UIButton 的子类来制作动画:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[UIView transitionWithView:self
duration:0.15
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{ self.highlighted = YES; }
completion:nil];
[super touchesBegan:touches withEvent:event];
}
然后在main的prepareForSegue方法中写这个ViewController:
if ([sender isKindOfClass:[UIButton class]]) {
UIButton* button = (UIButton*)sender;
[UIView transitionWithView:button
duration:0.15
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{ button.highlighted = NO; }
completion:nil];
}
这很好用,但是将单个动画的执行分成两个文件似乎不是最好的主意。有更好的方法吗?
P.S。在 touchesEnded 中使用代码的第二部分不起作用:(
您可以尝试在按钮的控件事件中执行突出显示,而不是使用 touchesBegan
和 touchesEnded
。
在您的 UIButton
子类中:
[self addTarget:self action:@selector(onTouchDown) forControlEvents:(UIControlEventTouchDown | UIControlEventTouchDragEnter)];
[self addTarget:self action:@selector(onTouchUp) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchDragExit | UIControlEventTouchCancel)];
事件方法:
-(void)onTouchDown
{
//perform your dissolve animation here
}
-(void)onTouchUp
{
//remove your dissolve animation here
}
我想在默认和突出显示的 UIButton 状态之间制作一个缓慢溶解的动画。按下按钮执行 segue,并将我们带到另一个 ViewController。我已经设法通过使用一种方法编写 UIButton 的子类来制作动画:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[UIView transitionWithView:self
duration:0.15
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{ self.highlighted = YES; }
completion:nil];
[super touchesBegan:touches withEvent:event];
}
然后在main的prepareForSegue方法中写这个ViewController:
if ([sender isKindOfClass:[UIButton class]]) {
UIButton* button = (UIButton*)sender;
[UIView transitionWithView:button
duration:0.15
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{ button.highlighted = NO; }
completion:nil];
}
这很好用,但是将单个动画的执行分成两个文件似乎不是最好的主意。有更好的方法吗?
P.S。在 touchesEnded 中使用代码的第二部分不起作用:(
您可以尝试在按钮的控件事件中执行突出显示,而不是使用 touchesBegan
和 touchesEnded
。
在您的 UIButton
子类中:
[self addTarget:self action:@selector(onTouchDown) forControlEvents:(UIControlEventTouchDown | UIControlEventTouchDragEnter)];
[self addTarget:self action:@selector(onTouchUp) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchDragExit | UIControlEventTouchCancel)];
事件方法:
-(void)onTouchDown
{
//perform your dissolve animation here
}
-(void)onTouchUp
{
//remove your dissolve animation here
}