ios - Swift 4.2 中计时器每秒倒计时时更新 UILabel

标签 ios swift timer countdown swift4.2

这里是新人,自学 Swift。构建我的第一个个人应用程序,但在此处、youtube 和 google 上多次搜索后却遇到了困难。这是我第一次发布问题(因为我可以在这里找到其他答案)。

我在 UILabel 上更新计时器时遇到问题。我设法在旧版本的 swift 上找到了让计时器运行并倒计时的代码。然后我想出了如何将秒分解为分钟和秒。

但我发现当我运行应用程序时,计时器显示“30:0”(我需要解决的另一个问题)并且从不倒计时。当我离开模拟器中的页面并返回时,UILabel 才会更新。

我知道 viewdidload 仅在页面打开的第一刻加载。我很难弄清楚如何让 UILabel 在每次更改时更新。我不确定要实现什么代码。

非常感谢!

import UIKit

var timer = Timer()
var timerDuration: Int = 1800

// This converts my timeDuration from seconds to minutes and seconds.
func secondsToHoursMinutesSeconds (seconds : Int) -> (h: Int, m : Int, s : Int) {
    return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}

class lyricWriteViewController: UIViewController {
    //This takes the function to convert minutes and seconds and accepts an input, which I've chosen the variable timeDuration (which is currently 1800 seconds.
    var theTimer = (h: 0, m: 0, s: 0)

    @IBOutlet weak var countdownTimer: UILabel!
    @IBOutlet weak var randomLyric: UILabel!
    @IBOutlet weak var titleInput: UITextField!
    @IBOutlet weak var lyricInput: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //This line takes a random array number and shows it on the textlabel.

        randomLyric.text = oneLiner
        theTimer = secondsToHoursMinutesSeconds(seconds: timerDuration)

        //This is the code the does the counting down
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(lyricWriteViewController.counter), userInfo: nil, repeats: true)
    }

    @objc func counter() {
        timerDuration -= 1

        // Below is the timer view I've created. It has converted seconds to minutes and seconds but the screen won't refresh. Also, when the seconds number hits zero, it does "0" instead of "00".
        let displayTimer = "\(theTimer.m) : \(theTimer.s)"
        countdownTimer.text = String(displayTimer)

        //When the timer hits 0, it stops working so that it doesn't go into negative numbers

        if timerDuration == 0 {
            timer.invalidate()
        }
    }

    func submitlyricsButton(_ sender: UIButton) {
        //I will eventually tie this to a completed lyric tableview.
    }
}

最佳答案

var timer: Timer?
var totalTime = 120

private func startOtpTimer() {
    self.totalTime = 120
    self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}

@objc func updateTimer() {
    print(self.totalTime)
    self.lblTimer.text = self.timeFormatted(self.totalTime) // will show timer
    
    if totalTime != 0 {
        totalTime -= 1 // decrease counter timer
    } 
    else {
        if let timer = self.timer { 
            timer.invalidate()
            self.timer = nil
        }
    }
}

func timeFormatted(_ totalSeconds: Int) -> String {
    let seconds: Int = totalSeconds % 60
    let minutes: Int = (totalSeconds / 60) % 60
    return String(format: "%02d:%02d", minutes, seconds)
}

关于ios - Swift 4.2 中计时器每秒倒计时时更新 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53008253/

相关文章:

objective-c - 关于 NSDateFormatter 和 NSCalendar 的问题(涉及时区)

ios - swift 图像中的标记功能

ios - 一次删除 Collection View 中的多个单元格的问题

ios - 状态栏背景颜色与 View Controller 不同

java - Android CountDownTimer 类滞后于主线程

c# - CF 中的计时器不计时

iphone - Sencha Touch 2 如何在 Windows 上构建 iOS 应用程序?

ios - 处理模拟器和设备之间的小数分隔符更改

ios - 使用 JsonModel 解析 json

java - 在Android中调用asynctask时出现计时器错误