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

时间:2015-06-25 12:53:11

标签: ios objective-c iphone animation uibutton

我想在默认和突出显示的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];
}

然后在主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];
    }

这很好用,但将单个动画的执行分成两个文件似乎不是最好的主意。有没有更好的方法呢?

P.S。在touchesEnded中使用代码的第二部分不起作用:(

1 个答案:

答案 0 :(得分:2)

您可以尝试在按钮的控件事件中执行突出显示,而不是使用touchesBegantouchesEnded

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
}