2015-11-13 80 views
0

我正在使用此代碼來分割段落,並用for循環寫入每個單詞,但我想每次迭代等待3秒。我怎樣才能做到這一點 ?延遲爲每個迭代之間的循環

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

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

回答

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是元素的索引)。

+0

由於這是工作:用於(ⅰ,字)在words.enumerate(){ dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64類型(I)*的Int64(3 * NSEC_PER_SEC)), dispatch_get_main_queue()){ self.fortuneContent.text! + =「\(word)」 } } – mTuran

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++ 
}