2015-07-09 20 views
1

嘗試在1秒後更新標籤。我正在使用睡眠功能,但應用程序正在加載,而不是即時更新文本字段。iOS Swift在1秒後更新文本標籤

代碼:

override func viewDidAppear(animated: Bool) { 
    beginCountdown() 
} 

func beginCountdown() { 

    for var i = 5; i >= 0; i-- { 

     println("Time until launch \(i)") 

     var county:String = "\(i)" 

     countdownLabel.text = county 
     sleep(1) 
    } 

} 

出口是正確的,我知道我失去了一些東西。謝謝

+0

您應該使用這一個NSTimer,有計時器重複每秒和更新標籤。然後在數到五之後關掉它。 –

+0

最後 - 我得到了println罰款 –

+1

永遠不要在主線程上使用'sleep'。 – rmaddy

回答

3

您不應該使用sleep()函數,因爲這將暫停主線程並導致您的應用程序變得無法響應。 NSTimer是實現此目的的一種方法。它將在未來的特定時間發送一個函數。

例如 -

var countdown=0 
var myTimer: NSTimer? = nil 

override func viewDidAppear(animated: Bool) {  
    countdown=5 
    myTimer = NSTimer(timeInterval: 1.0, target: self, selector:"countDownTick", userInfo: nil, repeats: true) 
    countdownLabel.text = "\(countdown)" 
} 

func countDownTick() { 
    countdown-- 

    if (countdown == 0) { 
     myTimer!.invalidate() 
     myTimer=nil 
    } 

    countdownLabel.text = "\(countdown)" 
} 
+0

感謝@Paul和其他人 - 使用了上面的NSTimer代碼並獲得了預期的結果。 –

+0

它不會freez UI。意味着你可以在UI上完成另一項任務。我正在尋找像這個代碼一樣在獨立線程中作爲背景的東西。但通過這種方式我的問題解決了。謝謝 –

0

你真的不應該使用sleep因爲它會阻止主線程,因此凍結UI,這意味着你永遠不會看到您的標籤更新(遠更糟糕的事情)。

您可以使用NSTimer實現您正在嘗試執行的操作。

var timer: NSTimer! 
var countdown: Int = 0 

override func viewDidAppear(animated: Bool) { 
    self.countdown = 5 
    self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateCountdown", userInfo: nil, repeats: true) 
} 

func updateCountdown() { 
    println("Time until launch \(self.countdown)") 
    countdownLabel.text = "\(self.countdown)" 

    self.countdown-- 

    if self.countdown == 0 { 
     self.timer.invalidate() 
     self.timer = nil 
    } 
} 
0

在雨燕3.0

var countdown=0 
var myTimer: Timer? = nil 

override func viewDidAppear(_ animated: Bool) { 
    countdown=5 
    myTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(Dashboard.countDownTick), userInfo: nil, repeats: true) 
    lbl_CustomerName.text = "\(countdown)" 
} 

func countDownTick() { 
    countdown = countdown - 1 
    //For infinite time 
    if (countdown == 0) { 
     countdown = 5 
     //till countdown value 
     /*myTimer!.invalidate() 
     myTimer=nil*/ 
    } 

    lbl_CustomerName.text = "\(countdown)" 
}