UIView shake animation

后端 未结 16 1305
梦毁少年i
梦毁少年i 2020-11-28 18:07

i\'m trying to make a UIView shake when a button is pressed.

I am adapting the code I found on http://www.cimgf.com/2008/02/27/core-animation-tutorial-window-shake-e

16条回答
  •  臣服心动
    2020-11-28 18:57

    I wrote that post. It's overkill for a UIView, plus the parameters are geared toward an OSX app. Do this instead.

    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"];
    

    You'll have to play with the duration and repeatCount parameters as well as the x distance from center in the from and to values, but it should give you what you need. I hope that helps. Let me know if you have any questions.

    ---


    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")
    

提交回复
热议问题