In my xcode project I have an UIImage. I want to make it shaking (animation) from left to right a little bit. I wrote this code, however, its not working.
-(void
Here's the code I use for that effect.
-(void)shakeView {
CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"position"];
[shake setDuration:0.1];
[shake setRepeatCount:2];
[shake setAutoreverses:YES];
[shake setFromValue:[NSValue valueWithCGPoint:
CGPointMake(lockImage.center.x - 5,lockImage.center.y)]];
[shake setToValue:[NSValue valueWithCGPoint:
CGPointMake(lockImage.center.x + 5, lockImage.center.y)]];
[lockImage.layer addAnimation:shake forKey:@"position"];
}
As Jere
mentioned. Make sure to include the import:
#import <QuartzCore/QuartzCore.h>
You can also add it as a category on UIView
.
brynbodayles answer also works under iOS8 for a shake animation in swift.
With Import of QuartzCore:
func shakeView(){
var shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
var from_point:CGPoint = CGPointMake(LoginField.center.x - 5, LoginField.center.y)
var from_value:NSValue = NSValue(CGPoint: from_point)
var to_point:CGPoint = CGPointMake(LoginField.center.x + 5, LoginField.center.y)
var to_value:NSValue = NSValue(CGPoint: to_point)
shake.fromValue = from_value
shake.toValue = to_value
LoginField.layer.addAnimation(shake, forKey: "position")
}
From Corona answer
Give shake animation in multiple buttons and also in views SWIFT3
for view animation just change extension UIButton to extension UIView
extension UIButton
{
func shakeAnim ()
{
let shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
let from_point:CGPoint = CGPoint(x:self.center.x - 5,y: self.center.y)
let from_value:NSValue = NSValue(cgPoint: from_point)
let to_point:CGPoint = CGPoint(x:self.center.x + 5,y: self.center.y)
let to_value:NSValue = NSValue(cgPoint: to_point)
shake.fromValue = from_value
shake.toValue = to_value
self.layer.add(shake, forKey: "position")
}
}
func shakeView(_ view: UIView?) {
let shake = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
shake.fromValue = NSValue(cgPoint: CGPoint(x: (view?.center.x)! - 5, y: view?.center.y ?? 0.0))
shake.toValue = NSValue(cgPoint: CGPoint(x: (view?.center.x)! + 5, y: view?.center.y ?? 0.0))
view?.layer.add(shake, forKey: "position")
}