1秒后iOS Swift更新文本标签

时间:2015-07-09 22:31:32

标签: ios swift uilabel

尝试在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)
    }

}

插座是正确的,我知道我错过了什么。感谢

3 个答案:

答案 0 :(得分: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)"
}

答案 1 :(得分:0)

你真的不应该使用sleep,因为它会阻止主线程,因此冻结用户界面,这意味着你永远不会看到你的标签更新(更糟糕的事情) )。

您可以使用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
    }
}

答案 2 :(得分:0)

在Swift 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)"
}