我有一個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