2

我目前正在制作一个快速动画。此动画由另一个函数在不稳定的时间间隔内触发(连接到服务器)。动画需要 2 秒才能完成,但它可能在完成之前被触发。这就是为什么我正在考虑创建一个等待队列来存储触发事件,直到动画完成并且可以重新启动。所以一方面我必须锁定动画功能,直到它再次准备好,另一方面我需要某种存储来存储传入的事件。我已经在考虑调度组,但不知道如何使用它们。对于我可以解决这个问题的方向的任何意见,我都会非常高兴。

触发功能:

private func subscribeToNewBLock() {
        DispatchQueue.global(qos:.userInteractive).async {
            watchForNewBlock() {result in
                switch result {
                case .Failure:
                    return
                case .Success(let result):
                    //Animation function
                    self.moveBlocksDown(blockNumber: result)
                    //Recursive call to keep listening for new blocks
                    self.subscribeToNewBLock()
                }
            }
       }
}
4

1 回答 1

0

您可以尝试制作动画队列,如下例所示

var results = [Int]()
var isAnimating = false

private func subscribeToNewBLock() {
    DispatchQueue.global(qos:.userInteractive).async {
        watchForNewBlock() {result in
            switch result {
            case .Failure:
                return
            case .Success(let result):

                //Call your UI operations in main thread
                DispatchQueue.main.async {

                    self.results.append(result)
                    //Animation function
                    self.moveBlocksDown()

                    //Recursive call to keep listening for new blocks
                    self.subscribeToNewBLock()
                }
            }
        }
    }
}

private func moveBlocksDown() {

    guard isAnimating == false && results.count > 0 else {

        return
    }

    self.moveBlocksDown(blockNumber: results.first!)

}

private func moveBlocksDown(blockNumber:Int){

    isAnimating = true

    UIView.animate(withDuration: 2.0, animations: {

        //Animation code goes here

    }) { (completed) in

        if completed{

            //Add follwing code in place of animation completed(May be in completion handler)
            self.isAnimating = false
            self.results = self.results.filter{$0 != blockNumber} //Remove already animated blockNumber
            self.moveBlocksDown() //Call moveBlocksDown function to check if anything pending in queue
        }
    }
}
于 2018-11-09T13:54:41.873 回答