【问题标题】:Formatting stopwatch's time in Swift在 Swift 中格式化秒表的时间
【发布时间】:2021-03-03 22:59:51
【问题描述】:

我正在尝试解决我的秒表问题。每 10 秒,在他以秒为单位结束时不是零,在 60 秒后不是 + 1 分钟。时间格式应为 m:ss (0:00)。开始和停止在我的应用程序中是相同的按钮。你能帮帮我吗?

var timer: Timer?
var isStarted = false
var counter = 0.00

@objc func updateTimeLabel() {
        counter += 0.01
        timerLabel.text = String(round(counter*1000)/1000)
      }


@IBAction func startStopButtonDidTouch(_ sender: UIButton) {
        if isStarted { //When tapped STOP
            timer?.invalidate()
            isStarted = false
            locationManager.stopUpdatingLocation()
            startStopButton.setTitle("START", for: .normal)
       
      } else { //When tapped START
        locationManager.startUpdatingLocation()
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimeLabel), userInfo: nil, repeats: true)
        isStarted = true
        startStopButton.setTitle("STOP", for: .normal)
       
        }
  }

【问题讨论】:

    标签: swift timer datetime-format stopwatch time-format


    【解决方案1】:

    有一个日期格式化程序可以将时间间隔显示为日期组件

    var counter : TimeInterval = 0
    
    let dateFormatter : DateComponentsFormatter = {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.minute, .second]
        formatter.zeroFormattingBehavior = .pad
        return formatter
    }()
    
    @objc func updateTimeLabel() {
        counter += 1
        timerLabel.text = dateFormatter.string(from: counter)!
    }
    

    【讨论】:

    • 感谢该解决方案对我很有帮助。你知道制作布局约束的简单方法吗??
    • 最简单的方法是Interface Builder。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多