0

I have a function that makes an image in my view "shake" back and forth. I can set how long I want it to shake and the speed, but what I really need is for it to shake every 10 seconds.

Here is the function I'm working with, it's simply called once in viewDidLoad to get it to work once.

    func shakeView(){

    let shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
    shake.duration = 0.4
    shake.repeatCount = 5
    shake.autoreverses = true
    shake.speed = 9.0

    let from_point:CGPoint = CGPointMake(homeLogo.center.x - 5, homeLogo.center.y)
    let from_value:NSValue = NSValue(CGPoint: from_point)

    let to_point:CGPoint = CGPointMake(homeLogo.center.x + 5, homeLogo.center.y)
    let to_value:NSValue = NSValue(CGPoint: to_point)

    shake.fromValue = from_value
    shake.toValue = to_value
    homeLogo.layer.addAnimation(shake, forKey: "position")
}

I haven't had any lucking finding out how I might be able to do this. Any help or pointing in the right direction would be greatly appreciated.

ALTVisual
  • 116
  • 10

4 Answers4

2

You need to use NSTimer. Use below code:

override func viewDidLoad() {
    super.viewDidLoad()
    var helloWorldTimer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: Selector("shakeView"), userInfo: nil, repeats: true)
} 
iVarun
  • 6,496
  • 2
  • 26
  • 34
1

Use timer for this.

[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(functionName) userInfo:nil repeats:YES];

Chirag kukreja
  • 433
  • 2
  • 5
1

Looks at this doc : https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/

There is a function named scheduledTimerWithTimeInterval that can execute a selector every time interval you specify

In swift : How can I use NSTimer in Swift?

Sample :

override func viewDidLoad() {
    super.viewDidLoad()
    //Swift 2.2 selector syntax
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
    //Swift <2.2 selector syntax
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
}
Community
  • 1
  • 1
Phoenix
  • 135
  • 3
  • 9
1

You wouldn't add that requirement to the animation, you'd create an NSTimer with the required period and use it to trigger each new animation.

You could move the animation and timer code into a custom image view class so that it can present a nice start and stop animating interface, then your view controller doesn't need to be complicated by timer management code (if you were to have multiple animating image views at the same time).

Wain
  • 118,658
  • 15
  • 128
  • 151