每2秒将变量发送到另一个函数

时间:2017-11-20 16:55:00

标签: swift timer

var routingmessage = ["TOAST1","TOAST2","TOAST3"]   

我正在尝试找到一种发送routingmessage 1值的方法,然后在2秒后将下一个发送给popup作为吐司。

例如我想:

TOAST1出现在00:00:00

TOAST2 00:00:02

TOAST3 00:00:04

我试过了:

for var i in (0..<routingmessage.count-1){
    var timerforToast = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(IndoorRouting.popupToast), userInfo: i, repeats: true)
}

但是在00:00:00时,一切都是流行的(TOAST1,TOAST2,TOAST3)

@objc func popupToast (val :Timer){
    let userInfo = val.userInfo as! Int

    //toast appear
    self.view.makeToast(routingmessage[i], duration: 1.0, point: CGPoint(x: 110.0, y: 110.0), title: "Toast Title", image: UIImage(named: "toast.png")) { didTap in
        if didTap {
            print("completion from tap")
        } else {
            print("completion without tap")
        }
    }
}

1 个答案:

答案 0 :(得分:1)

asyncAfter怎么样?

let durationBetweenToasts: Double = 10
for i in (0 ..< routingMessage.count) {
    let deadline: DispatchTime = .now() + (Double(i) * durationBetweenToasts)
    DispatchQueue.main.asyncAfter(deadline: deadline) {
        popupToast()
    }
}