简体   繁体   English

如何在状态之间正确设置UIButton的动画?

[英]How to properly animate UIButton between states?

I wanted to make a slow dissolve animation between the Default and Highlighted UIButton state. 我想在Default和Highlighted UIButton状态之间制作一个缓慢的溶解动画。 Pressing the button performs a segue, and takes us to another ViewController. 按下按钮将执行搜索,然后将我们带到另一个ViewController。 I have managed to do the animation by writing a subclass of UIButton with a single method: 我已经通过使用单个方法编写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];
}

And then writing this in the prepareForSegue method of the main ViewController: 然后将其写入主ViewController的prepareForSegue方法中:

if ([sender isKindOfClass:[UIButton class]]) {
        UIButton* button = (UIButton*)sender;
        [UIView transitionWithView:button
                          duration:0.15
                           options:UIViewAnimationOptionTransitionCrossDissolve
                        animations:^{ button.highlighted = NO; }
                        completion:nil];
    }

This works well, but dividing the execution of a single animation into two files does not seem to be the best idea. 这很好用,但是将单个动画的执行分成两个文件似乎不是最好的主意。 Is there a better way of doing this? 有更好的方法吗?

PS using the second part of code in touchesEnded does not work :( PS在touchesEnded中使用代码的第二部分不起作用:(

Instead of using touchesBegan and touchesEnded you can try to perform the highlighting in the control events of the button. 除了尝试使用touchesBegantouchesEnded您还可以尝试在按钮的控制事件中执行突出显示。

In your UIButton subclass: 在您的UIButton子类中:

[self addTarget:self action:@selector(onTouchDown) forControlEvents:(UIControlEventTouchDown | UIControlEventTouchDragEnter)];
[self addTarget:self action:@selector(onTouchUp) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchDragExit | UIControlEventTouchCancel)];

The event methods: 事件方法:

-(void)onTouchDown
{
    //perform your dissolve animation here
}

-(void)onTouchUp
{
    //remove your dissolve animation here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM