当按下按钮时,我试图使UIView震动.

我正在修改我在http://www.cimgf.com/2008/02/27/core-animation-tutorial-window-shake-effect/上找到的代码.

但是,通过try 调整以下代码来抖动UIView,它不起作用:

- (void)animate {
    const int numberOfShakes = 8;
    const float durationOfShake = 0.5f;
    const float vigourOfShake = 0.1f;

    CAKeyframeAnimation *shakeAnimation = [CAKeyframeAnimation animation];

    CGRect frame = lockView.frame;

    CGMutablePathRef shakePath = CGPathCreateMutable();
    CGPathMoveToPoint(shakePath, NULL, CGRectGetMinX(frame), CGRectGetMinY(frame));

    for (int index = 0; index < numberOfShakes; ++index) {
        CGPathAddLineToPoint(shakePath, NULL, CGRectGetMinX(frame) - frame.size.width * vigourOfShake, CGRectGetMinY(frame));

        CGPathAddLineToPoint(shakePath, NULL, CGRectGetMinX(frame) + frame.size.width * vigourOfShake, CGRectGetMinY(frame));
    }

    CGPathCloseSubpath(shakePath);

    shakeAnimation.path = shakePath;
    shakeAnimation.duration = durationOfShake;


    [lockView.layer addAnimation:shakeAnimation forKey:@"frameOrigin"];

}

推荐答案

那篇帖子是我写的.对于UIView来说,这太过分了,而且这些参数都是针对OSX应用的.这样做吧.

CABasicAnimation *animation = 
                         [CABasicAnimation animationWithKeyPath:@"position"];
[animation setDuration:0.05];
[animation setRepeatCount:8];
[animation setAutoreverses:YES];
[animation setFromValue:[NSValue valueWithCGPoint:
               CGPointMake([lockView center].x - 20.0f, [lockView center].y)]];
[animation setToValue:[NSValue valueWithCGPoint:
               CGPointMake([lockView center].x + 20.0f, [lockView center].y)]];
[[lockView layer] addAnimation:animation forKey:@"position"];

您必须使用Duration和RepeatCount参数,以及From和To值中距中心的x距离,但它应该可以满足您的需要.我希望这能帮上忙.如果你有任何问题,请告诉我.

---


Swift 3.0

let midX = lockView.center.x
let midY = lockView.center.y

let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.06
animation.repeatCount = 4
animation.autoreverses = true
animation.fromValue = CGPoint(x: midX - 10, y: midY)
animation.toValue = CGPoint(x: midX + 10, y: midY)
layer.add(animation, forKey: "position")

Ios相关问答推荐

无法在fastlane和github操作中从react-native 应用程序构建ios

使用CGAffineTransform旋转视图只起作用一次吗?

使用SWIFT传输表示时的条件文件表示格式

如何使用自定义数据源在本地react 本机 ios 应用程序中加载 Tradingview 小部件?

为什么applicationState发布者只发布一次?

多协议和类继承混乱,Swift

不可发送类型 '[String : Any]?'在调用非隔离实例方法 XXX 时退出主参与者隔离上下文不能跨越参与者边界

如何让替换视图淡入旧视图而不是交叉淡入淡出?

迁移到 UIKit 生命周期的应用程序不会调用 SceneDelegate

在 Swift 中合并子数组

如何在通用应用程序中同时支持 iPad 和 iPhone 视网膜图形

在 iOS 中获取设备位置(仅限国家/地区)

如何从一个特定的视图控制器中隐藏导航栏

在 Grand Central Dispatch 中使用 dispatch_sync

有没有办法在 xib 文件中的视图和顶部布局指南之间添加约束?

如何在上传到服务器之前在 iOS 上压缩/调整图像大小?

刷新由 Xcode 7 管理的团队配置文件中的设备?

将自定义对象保存到 NSUserDefaults

以编程方式创建按钮并设置背景图像

iOS 7 及更高版本: for each 视图控制器设置状态栏样式