ALTVisual
ALTVisual

Reputation: 116

Repeat function on time interval?

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.

Upvotes: 0

Views: 1075

Answers (4)

iVarun
iVarun

Reputation: 6611

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

Upvotes: 2

Wain
Wain

Reputation: 119031

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

Upvotes: 1

Phoenix
Phoenix

Reputation: 145

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

Upvotes: 1

Chirag kukreja
Chirag kukreja

Reputation: 433

Use timer for this.

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

Upvotes: 1

Related Questions