延迟每次迭代之间的循环

时间:2015-11-13 19:58:42

标签: ios swift

我正在使用此代码来分割段落并使用for循环写入每个单词但我希望每次迭代等待3秒。我怎样才能做到这一点 ?

let words = fortuneContentText.characters.split{$0 == " "}.map(String.init)

for word in words {
  fortuneContent.text! += "\(word) "
}

2 个答案:

答案 0 :(得分:3)

这几乎肯定不会像你期望的那样做任何事情。您无法阻止UI线程。您需要安排更新。像这样的东西可以工作(未经测试;可能不会按照书面编译,但基本的想法):

for (i, word) in words.enumerate() {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, i*3*NSEC_PER_SEC),
                   dispatch_get_main_queue()) {
                       fortuneContent.text! += "\(word) "
    }
}

我们的想法是,您希望每次更新都安排在您希望它发生的时间点(3*i,其中i是元素的索引。

答案 1 :(得分:1)

您可以保留打印字数并使用计时器。

//==========================================================
//as a member variable or some variable that persists outside function calls
var nWords = 0
var mainWords:[String]

//==========================================================
//in a method or wherever you normally have this code
let words = fortuneContentText.characters.split{$0 == " "}.map(String.init)
mainWords = words

NSTimer.scheduledTimerWithTimeInterval(3, target:self, selector:"printWord:", userInfo:nil, repeats:true)

//==========================================================
//the timer function
func printWord(timer:NSTimer)
{
    if (nWords == mainWords.count)
    {
        timer.invalidate()   //stop the timer (stop printing words)
        return
    }

    fortuneContent.text! += "\(mainWords[nWords]) "
    nWords++
}