【问题标题】:For In Loop animations being skipped when the array contains duplicates当数组包含重复项时跳过循环内动画
【发布时间】:2021-09-29 15:14:58
【问题描述】:

我有一个函数,它遍历 UIButtons 数组并为数组中的每个按钮一个一个地设置动画。目前这一切都很好,直到一个按钮被多次附加到数组中,然后它跳过两个实例的动画。有没有办法阻止这种行为?

func animateButtons() {
        disableButtons()

        for (index, button) in buttonSequence.enumerated() {
            group.enter()
            UIButton.animate(
                withDuration: 1,
                delay: TimeInterval(index),
                animations: {
                    button.backgroundColor = UIColor(red: 63/255, green: 255/255, blue: 0/255, alpha: 1.0)
                },
                completion: { finished in
                    button.backgroundColor = UIColor(red: 168/255, green: 61/255, blue: 164/255, alpha: 0.85)
                    self.group.leave()
                }
            )
        }

        group.notify(queue: .main) {
            self.enableButtons()
        }
    }

【问题讨论】:

  • 如果你想让按钮一个接一个地动画,为什么不在迭代时给动画添加延迟?
  • 这是对调度组的滥用。您应该通过完成处理程序进行递归,或使用关键帧。

标签: arrays swift for-loop animation uibutton


【解决方案1】:

问题是您的带有人工delay 参数的for 循环是完全错误的。链接动画的方法是使用关键帧动画或使用递归。在这种情况下,我建议递归。这是一个简单的工作示例;这是一个带有两个按钮的应用的完整代码,外加一些触发start功能的方法,所以你自己试试吧:

func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
class ViewController: UIViewController {
    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var button2: UIButton!
    func start() {
        // starting, disable buttons
        let buttonSequence : [UIButton] = [ button1, button2, button1, button1, button2 ]
        self.animate(buttonSequence)
    }
    func animate(_ seq:[UIButton]) {
        if let b = seq.first {
            UIView.animate(withDuration: 1, delay: 0, options: [], animations: {
                b.backgroundColor = .red
            }) { _ in
                b.backgroundColor = nil
                delay(0.1) {
                    self.animate(Array(seq.dropFirst()))
                }
            }
        } else {
            // done, enable buttons
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 2014-08-29
    • 2016-05-06
    • 2014-07-20
    相关资源
    最近更新 更多