Swift循环遍历数组,中间有暂停

问题描述 投票:0回答:1

我正在尝试使用一个循环遍历Ints数组的函数,对于每个项目,根据其值,弹出一个特定的消息一秒左右,然后让消息消失,然后继续数组中的下一个项目。我能够弄清楚如何使用DISPATCH为消息消失创建一个“延迟” - 但我仍然最终会立即弹出所有消息。

另外,我创建了一个名为“offAll()”的函数来关闭所有消息,我试图在for循环结束时使用DISPATCH调用 - 但正如我所说,它仍然会立即显示所有消息。 (我也尝试将DISPATCH语句分别放入每个case语句中,但这似乎也没有帮助。)

仅供参考,我在XCode中使用Swift 4。谢谢!!

 func popUp(){
    for item in order{
        if item == 0 {
            firstLabel.text = "ME!"
        } else if item == 1 {
            secondLabel.text = "ME!"
        } else if item == 2 {
            thirdLabel.text = "ME!"
        } else {
            fourthLabel.text = "ME!"
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
          self.offAll()
        }

    }
arrays swift loops delay dispatch
1个回答
2
投票

消息一起显示,因为for循环不是异步的,并且您没有暂停它。解决方案可能是使用计时器来延迟每条消息。您可以在任何想要开始显示消息的地方调用此计时器。我假设订单是一个数组。

    var item = 0
    let popUpTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
        //removes all popups
        self.offAll()
        if item == 0 {
            firstLabel.text = "ME!"
        } else if item == 1 {
            secondLabel.text = "ME!"
        } else if item == 2 {
            thirdLabel.text = "ME!"
        } else {
            fourthLabel.text = "ME!"
        }
        item = item + 1
        if item >= order.count { //not order.count - 1 so the last popup can be removed
            //stops the timer when all popups are shown
            timer.invalidate()
        }
    })

这将在每秒显示一个弹出窗口,并在显示下一个弹出窗口之前将其删除。

© www.soinside.com 2019 - 2024. All rights reserved.