【问题标题】:All digits not shown in timer countdown计时器倒计时中未显示的所有数字
【发布时间】:2019-01-17 10:04:28
【问题描述】:

在进入视图时,我调用一个函数来加载一个计时器,就像这样......

var count = 10

 func startTimer() {
         timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
  }

update 函数被赋予为..

@objc func update() {
    while (count != 0) {
      count -= 1
      countdownLabel.text = "\(count)"

    }
     timer.invalidate()
  }

但是当我看到这个视图时,会直接显示数字 0,而不是理想地显示序列中的所有数字 9,8,7,6,5,4,3,2,1,0

我在这里做错了什么..?

【问题讨论】:

  • while (count != 0) { count -= 1; ... },想想那个循环在几秒钟内做了什么:它一次计数到 0,然后立即使你的计时器失效。

标签: ios swift nstimer


【解决方案1】:

斯威夫特 4:

    var totalTime = 10
    var countdownTimer: Timer!

    @IBOutlet weak var timeLabel: UILabel!

    override func viewDidLoad() {
      super.viewDidLoad()
      startTimer()
    }

此方法调用初始化计时器。它指定 timeInterval(调用 a 方法的频率)和选择器(调用的方法)。

时间间隔以秒为单位,因此为了让它像标准时钟一样运行,我们应该将此参数设置为 1。

    func startTimer() {
         countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }

// Stops the timer from ever firing again and requests its removal from its run loop.
   func endTimer() {
       countdownTimer.invalidate()
   }

  //updateTimer is the name of the method that will be called at each second. This method will update the label
   @objc func updateTime() {
      timeLabel.text = "\(totalTime)"

       if totalTime != 0 {
          totalTime -= 1
       } else {
          endTimer()
       }
   }

【讨论】:

  • 如果他们解释问题和解决方案,而不是转储代码代码,答案会更有帮助(对 OP 和未来的读者)。
  • @HiềnĐỗ 现在学习,edit 你的答案。
  • 感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多