【问题标题】:Swift: For loop - wait for animation to complete before iterationSwift:For循环 - 在迭代之前等待动画完成
【发布时间】:2018-02-08 10:57:03
【问题描述】:

我正在尝试显示基于随机数组的动画序列。

在我的 ViewController 上,我有 4 个带有标签 (1,2,3,4) 的 UIButton。

然后我有一个 shuffledArray

shuffledArray = [3,2,4,1]

我正在使用 for 循环遍历该数组并像这样为 UIButton 的背景设置动画:

for square in shuffledArray {
        let btn = view.viewWithTag(square)
        
        UIView.animate(withDuration: 1, delay: 0.0, options:[], animations: {
            btn?.backgroundColor = .red
            btn?.backgroundColor = .black
            btn?.backgroundColor = .red
        }, completion: nil)
 }

不过,这只会让 4 个方格同时变黑。

有没有办法运行这个循环,但要等待每个动画首先触发,然后再迭代到数组的下一个索引?

我尝试使用:

sleep(4)

for 循环结束,但这似乎冻结了我的应用程序,然后所有 4 个方块再次同时发生变化。

旁注

这个 for 循环在按钮点击时被激活。在 for 循环运行后,我将生成一个介于 1 和 4 之间的随机数,然后将其附加到 shuffledArray。所以它开始于:

 shuffledArray = [3]

那就是第二次了

 shuffledArray = [3,2]

第三个

 shuffledArray = [3,2,4]

等等……

这个问题似乎只发生在数组包含超过 1 个项目时。

【问题讨论】:

    标签: ios swift animation uibutton


    【解决方案1】:

    试试这样的? (未测试)

    var currentIndex = 0 
    func animateNext() {
        if currentIndex < shuffledArray.count {  
            let btn = view.viewWithTag(shuffledArray[currentIndex])
            UIView.animate(withDuration: 1, delay: 0.0, options:[.autoreverse], animations: {
                btn?.backgroundColor = .red
                btn?.backgroundColor = .black
            }) { _ in
                self.currentIndex += 1
                self.animateNext()
            }
        }
    }
    

    【讨论】:

    • shuffedArray 得到两个项目的那一刻,它不会将任何正方形变成黑色。
    • 在调用animateNext()之前将currentIndex重置为0
    • 另外,尝试使用.autoreverse 来创建更好的闪烁效果。
    【解决方案2】:

    尝试使用延迟属性,如下所示:

    for (index, square) in shuffledArray.enumerated() {
            let btn = view.viewWithTag(square)
    
            UIView.animate(withDuration: 1, delay: index, options:[], animations: {
                btn?.backgroundColor = .red
                btn?.backgroundColor = .black
                btn?.backgroundColor = .red
            }, completion: nil)
        }
    

    更新:

    【讨论】:

    • 这个解决方案可能会更好,因为它更简单。
    • 这适用于第一个,然后它似乎将其他 3 个跳在一起。
    • @JamesG 你确定每个按钮都有正确的标签吗?
    • @NikitaErmolenko 是的。刚刚检查过。
    • @JamesG 你可以为测试增加延迟吗?类似的东西:延迟* 3。并在慢速模拟器模式下检查动画。
    猜你喜欢
    • 2020-11-18
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多