利用CAKeyFrameAnimation实现仿MAC登录界面密码不正确晃动效果

产品有时候会提一些不切实际的需求,比如下面这个:非要在iOS设备上实现登录输入密码不正确时密码框晃动3次的需求。纵观我见过的应用,还没有见过输入框带这种效果的。不过既然要实现,就要想办法争取做出来。
 
最初我的想法是用UIView的animation代码块来实现,效果也可以,代码如下:

    CGPoint originCenter = textField.center;

    [UIView animateWithDuration:SHAKE_ONCE_DURATION /2 animations:^{

        textField.center =CGPointMake(originCenter.x - INPUT_PASSWORD_SHAKE_OFFSET, originCenter.y);

    } completion:^(BOOL finished){

        [UIView animateWithDuration:SHAKE_ONCE_DURATION delay:0 options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat animations:^{

            [UIView setAnimationRepeatCount:2.5];

            textField.center =CGPointMake(originCenter.x + INPUT_PASSWORD_SHAKE_OFFSET, originCenter.y);

        } completion:^(BOOL finished){

            [UIView animateWithDuration:SHAKE_ONCE_DURATION /2 animations:^{

                textField.center =CGPointMake(originCenter.x, originCenter.y);

            } completion:^(BOOL finished){

            }];

        }];

    }];

 
主要思想是运用语句块的completion实现动画嵌套。但是这段代码别人不容易读懂,后期维护起来有点困难。
最近正在学习关键帧动画技术(CAKeyframeAnimation),于是我尝试用关键帧动画实现这个需求,上代码。

    //创建关键帧动画

    CAKeyframeAnimation *keyFrame = [CAKeyframeAnimationanimationWithKeyPath:@"position"];

    //设置各个关键帧位置

    keyFrame.values = @[[NSValuevalueWithCGPoint:CGPointMake(524, 329)],

                        [NSValuevalueWithCGPoint:CGPointMake(519, 329)],

                        [NSValuevalueWithCGPoint:CGPointMake(529, 329)],

                        [NSValuevalueWithCGPoint:CGPointMake(519, 329)],

                        [NSValuevalueWithCGPoint:CGPointMake(529, 329)],

                        [NSValuevalueWithCGPoint:CGPointMake(519, 329)],

                        [NSValuevalueWithCGPoint:CGPointMake(529, 329)],

                        [NSValuevalueWithCGPoint:CGPointMake(524, 329)]];

    //淡入淡出效果

    keyFrame.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    //动画持续时间

    keyFrame.duration = 0.5;

    //恢复到最初位置

    self.passwordTextField.layer.position = CGPointMake(524, 329);

    //密码输入框图层加入动画

    [self.passwordTextField.layeraddAnimation:keyFrame forKey:@"keyFrame"];

 

关键帧顾名思义,就是设置view的各个关键帧,然后就会按照设置好的坐标进行动画。需要注意的是关键帧动画是隐式动画,即动画执行完不保留最终位置。还有就是需要导入QuartzCore头文件。

转自:http://blog.163.com/nijino_saki/blog/static/8009214420132155585685/

原文地址:https://www.cnblogs.com/codings/p/3634392.html