ecoguy ecoguy - 5 months ago 32
iOS Question

Detecting if SKAction is done running, Swift

I want to change the value of a variable after an action has been run and not during it is running. This is my code:

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {

if gameNotStarted {
if firePosition.x != 320 || firePosition.y > 280 {
fire.runAction(fireButtonReturn)
iapButton.runAction(iapButtonReturn)
aboutButton.runAction(abtButtonReturn)

if fire.hasActions() == false {
println("has no actions")
firePosition.x = 320
firePosition.y = 280
}
}
}
}


The three actions I am running have exactly the same duration so I only need one to check if they have finished running. After they have finished running I want to change the value of
firePosition.x
and
firePosition.y
.
It is very important that fire position values change exactly after the action has been run and absolutely not before the actions are done running.

However with my current code I never run the
if fire.hasActions() ...
part according to results and console.
I found similar questions, they were in obj-c.
Thanks for your help.

Answer

You should use a completion-handler for your kind of problem:

//Run the action
iapButton.runAction(iapButtonReturn,
    //After action is done, just call the completion-handler.
    completion: {
        firePosition.x = 320
        firePosition.y = 280
    }
)

Or you could use a SKAction.sequence and add your actions inside a SKAction.block:

var block = SKAction.runBlock({
    fire.runAction(fireButtonReturn)
    iapButton.runAction(iapButtonReturn)
    aboutButton.runAction(abtButtonReturn)
})

var finish = SKAction.runBlock({
    firePosition.x = 320
    firePosition.y = 280
})

var sequence = SKAction.sequence([block, SKAction.waitForDuration(yourWaitDuration), finish])

self.runAction(sequence)