从当前状态动画UIButton

时间:2014-10-23 19:17:34

标签: ios objective-c animation

我想创建具有“弹性”按下动画的按钮。 动画描述:

On press: 
scale it on 80% in 0.1s
scale it on 90% in 0.1s // when pressed it should stay at 90% scale

On release: 
scale it on 110% in 0.1s
scale it on 100% in 0.1s // when released - scale should finish at 100%

我尝试用代码实现这个:

-(void) pressedAnimation {
  [UIView animateWithDuration:kAnimationTime
                      delay:0.0
                    options: UIViewAnimationOptionBeginFromCurrentState

                 animations:^{

                     self.transform = CGAffineTransformMakeScale(.8f, .8f);
                 }completion:^(BOOL finished){
                     if (finished) {
                         [UIView animateWithDuration:kAnimationTime
                                               delay:0.0
                                             options: UIViewAnimationOptionBeginFromCurrentState
                                          animations:^{
                                              self.transform = CGAffineTransformMakeScale(.9f, .9f);
                                          }completion:^(BOOL finished){
                                          }];
                     }

                 }];
}

-(void) releasedAnimation {
  [UIView animateWithDuration:kAnimationTime
                      delay:0.0
                    options: UIViewAnimationOptionBeginFromCurrentState
                 animations:^{

                     self.transform = CGAffineTransformMakeScale(1.1f, 1.1f);
                 }completion:^(BOOL finished){
                     if (finished) {
                        [self.layer removeAllAnimations];
                         [UIView animateWithDuration:kAnimationTime
                                               delay:0.0
                                             options:UIViewAnimationOptionBeginFromCurrentState
                                          animations:^{
                                              self.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
                                          }completion:^(BOOL finished){
                                          }];
                     }

                 }];
}

只有在“pressedAnimation”已经完成时调用“releasedAnimation”时,动画才会按预期工作。否则我的效果非常奇怪。

我尝试在两种方法中使用[self.layer removeAllAnimations],但它不能按预期工作。似乎UIViewAnimationOptionBeginFromCurrentState不起作用。我究竟做错了什么?有没有更好的方法来创建这样的动画?

1 个答案:

答案 0 :(得分:0)

您可以将此行为抽象为实用程序类。尝试这样的事情:

对于.h:

+(void)buttonBobble:(UIButton *)button actionWhenDone:(void(^)(BOOL))action;

对于.m:

+(void)buttonBobble:(UIButton *)button actionWhenDone:(void (^)(BOOL))action
{
    button.transform = CGAffineTransformMakeScale(0.8f, 0.8f);
    [UIView animateWithDuration:0.5f animations:^{
        button.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
    }completion:action];
}

当然,您可能需要调整一下,以获得您想要的正确外观。如果您希望在按钮所在的位置选择UIViewAnimationOptionBeginFromCurrentState,您还需要添加{{1}}。