【问题标题】:iOS Swift Update text label after 1 secondiOS Swift 1 秒后更新文本标签
【发布时间】:2015-07-09 22:31:31
【问题描述】:

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

}

出口是正确的,我知道我错过了一些东西。谢谢

【问题讨论】:

  • 您应该为此使用 NSTimer,让计时器每秒重复一次并更新标签。数到五后将其关闭。
  • 最后 - 我得到了 println 罚款
  • 永远不要在主线程上使用sleep
  • UI 只能在有机会执行时才能绘制。您的代码所做的是在循环执行时阻塞,UI 无法更新,直到代码被解除阻塞,因此它没有您想要的效果,并且您的 UI 代码在倒计时期间没有更新,只有在它完成之后。您需要使用 NSTimer,这将允许代码在倒计时期间解除阻塞并运行,而不是在倒计时之后,这样做将允许 UI 绘制。

标签: ios swift uilabel


【解决方案1】:

您不应该使用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)"
}

【讨论】:

  • 感谢@Paul 和其他人 - 使用上面的 NSTimer 代码并得到了预期的结果。
  • 它不会冻结 UI。意思是虽然你可以在 ui 上做另一项任务。我正在搜索类似此代码的代码,该代码在单独的线程中用作背景。但这样我的问题就解决了。谢谢
【解决方案2】:

你真的不应该使用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
    }
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 2016-06-03
      相关资源
      最近更新 更多