2015-10-05 57 views
0

我想在視圖出現時動畫UILabel的值。爲此我創建了這個功能。動畫增量UILabel

private func animateIncrementUILabel(label: SpringLabel, labelValue: Int, animationPeriod: Float?) 
{ 

    animationPeriod != nil ? animationPeriod! : 40 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { 

     for (var i = 0; i < labelValue; i++) 
     { 
      usleep(UInt32(animationPeriod!)/100 * 1000000) 
      dispatch_async(dispatch_get_main_queue(), { 
       label.text = String(i) 
      }) 
     } 

    }) 
} 

但在我的viewDidAppear方法調用這個時候像

animateIncrementUILabel(counterLabelOne, labelValue: 20, animationPeriod: 40.0) 

它顯示在標籤馬上沒有「動畫incremention」的值。

我在這裏做錯了什麼?

+0

刪除這些調度塊和使用的NSTimer .Schdule活動,而不是睡眠 –

回答

2

在這種情況下請勿使用usleepdispatch_async。我建議你使用dispatch_after

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(i * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
    <#code to be executed after a specified delay#> 
}); 

或使用的NSTimer重複選項

NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true) 

您也可以通過一些PARAMS定時器:

func someFunc(){ 
    var arr = ["one", "two"] 
    var timer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("val:"), userInfo: arr, repeats: true) 
} 

func val(timer: NSTimer){ 

    //You'll get an array in timer.userInfo 
    // arr = timer.userInfo. 
    // Now you'll get you data in each index of arr 

} 
+0

但我想給幾個參數..我如何實現與NSTimer?你能舉個例子嗎? – Reshad

+0

@Reshad高於 – Arsen

+0

,但這種方式我不能強制給出某些參數。其全部可選 – Reshad