我有一个for循环执行动画,然后完成删除它们,我试图在完成时调用另一个方法。这是我的代码:For循环在swift似乎随机选择增量
func animateMatch(completion:() ->()) {
var movingShape = level.shapeAtColumn(pointsContainingShapeArray[0].Column, row: pointsContainingShapeArray[0].Row)
let destinationShape = level.shapeAtColumn(pointsContainingShapeArray[0].Column, row: pointsContainingShapeArray[0].Row)
for everyShape in 1..<pointsContainingShapeArray.count {
movingShape = level.shapeAtColumn(pointsContainingShapeArray[everyShape].Column, row: pointsContainingShapeArray[everyShape].Row)
let Duration: NSTimeInterval = 1
let moveShapes = SKAction.moveTo((destinationShape?.sprite!.position)!,duration: Duration)
moveShapes.timingMode = .EaseOut
movingShape?.sprite?.runAction(moveShapes, completion: {
movingShape?.sprite?.removeFromParent()
print("Removed shape \(everyShape)")
if everyShape == pointsContainingShapeArray.count {
completion()
}
})
}
}
基本上这个想法是,所述第一位置之后的阵列中的每个的形状移动到第一个的位置,然后从场景中删除。这工作正常,但我的完成每次都随机调用。所以最后我在那里添加了打印语句。这里是输出:
Removed shape 3
Removed shape 1
Removed shape 4
Removed shape 2
在这一点上,我非常沮丧,我决定是时候堆栈溢出。我无法弄清楚这里发生了什么。谢谢你的帮助!
这里是调用此方法的代码:
func handleSwipe(move: Move) {
view.userInteractionEnabled = false
level.performMove(move)
scene.animateMove(move) {
self.view.userInteractionEnabled = true
if hasMatch {
self.view.userInteractionEnabled = false
self.scene.animateMatch() {
self.scene.addNewSpritesForShapes(pointsContainingShapeArray)
hasMatch = false
self.view!.userInteractionEnabled = true
}
}
}
}
'runAction'是一个异步操作。这是表现得如预期。 :p – Moritz
关于我应该如何设置这个以我想要的方式工作的任何想法? – SomeGuy
您可以使用'dispatch_apply'按顺序运行循环及其块。我相信还有很多其他的选择:使用NSOperations,只有在A完成后才使用回调来启动B等。 – Moritz