2016-04-04 63 views
-3

我有一個UILabel需要在一段時間後將其文本更改爲數組中的下一個項目。我正在使用for-in循環來實現這一點。不過,我的問題是,標籤在循環完成之前不會改變,這會破壞目的。我做了很多搜索,看起來好像使用dispatch_async(dispatch_get_main_queue()...就是這樣做的方式,我試圖像其他人一樣使用它,但它不會更新標籤的文本。所以,如果有人可以幫助我使用它在我的代碼,或者有一個解決方案,以更新循環的文本,我們將不勝感激更新循環中的UILabel文本

我的代碼:

@IBAction func startEndTouch(sender: AnyObject) { 

var wordsPerMinVal:Double = 60.0/sliderValueBen 

for item in textEnterGo { 
    delay(wordsPerMinVal){ 
     self.yourWordsLabel.text = item 
     print(item) 
    } 
} 
} 

兩個地方,我得到了一些信息來自:

dslkfjsdlfjl & Rob

Vacawama

+0

在一個簡單的'for'循環你不能做到這一點。想想看。 'delay'延遲花括號內的內容,但不會延遲您的代碼 - 也就是說,它不會延遲循環本身。循環以閃電般的速度運行,所以你所有的'delay'子句,它們具有相同的'wordsPerMinVal',或多或少地同時執行(當然後面)。 – matt

+0

@matt感謝您的解釋。我的應用能夠以我想要的方式工作嗎? –

回答

2

嘗試:

var textEnterGo:[String] = ["1","2","3","4","5","6","7","8","9","10"] 
var wordsPerMinVal:Double = 0 
var timer:NSTimer? 
@IBAction func startEndTouch(sender: AnyObject) { 
    if timer != nil{ 
     index = 0 
     self.lblText.text = "" 
     timer!.invalidate() 
     timer = nil 
    } 
    wordsPerMinVal = 1 
    self.timer = NSTimer.scheduledTimerWithTimeInterval(self.wordsPerMinVal, target: self, selector: #selector(ViewController.setTextForLabel), userInfo: nil, repeats: true) 
} 

var index:Int = 0 
func setTextForLabel(){ 
    self.lblText.text = self.textEnterGo[index] 
    index += 1 
    if index > self.textEnterGo.count-1{ 
     index = 0 
    } 
}