首页 > 解决方案 > swift:从数组中多次调用动作

问题描述

我有 int 值的数组:

var array = [1,82,17,29,74,94,76,97,48,78,88,20,31]

和行动:

@IBAction func action(_ sender: Any) {
        print("i")
    }

我想为数组中的值调用我的操作。

例如:第一次动作在 1 秒后调用,下一次在 82 秒后调用,下一次在 17 秒后调用。等等...

怎么做?

标签: iosswift

解决方案


使用下面的代码来实现这一点。

    var count = 0
    let seconds = array[count] // get initial value
    _ = Timer.scheduledTimer(timeInterval: seconds, target: self, selector: #selector(callMethod), userInfo: nil, repeats: false)

@objc func callMethod() {
    print("CallMethod....")
    count += 1
    if count < array.count {
    let nextTime = array[count] // get next time value
    _ = Timer.scheduledTimer(timeInterval: nextTime, target: self, selector: #selector(callMethod), userInfo: nil, repeats: false)
 }
}

推荐阅读