我需要使用 timeIntervalSince() 方法在 Swift 中創建一個簡單的秒表。我真的不明白如何使用 timeIntervalSince (我需要什么以及如何實作它)以及如何將其轉換為一個字串,它將向我顯示過去的時間,如“00:00:00”。
我知道我需要使用計時器來更新標簽并在單擊“停止”時使其無效。
我真的很感激這方面的任何幫助。如果您需要更多資訊,請與我們聯系。
uj5u.com熱心網友回復:
該方法timeIntervalSince(_:)是一種方法Date。它為您提供自其他日期和您詢問的日期以來經過的秒數。
所以,
創建一個秒表VC。給 StopwatchVC 一個startTimeDate 型別的 var。也給它一個Timervar。讓我們稱之為updateTimer。
當用戶點擊開始按鈕時,將Date()(現在的時間)保存到 startTime。還要啟動一個重復計時器,updateTimer它每 1/10 秒觸發一次。(或者無論您想更新秒表的頻率如何,但請注意,快于 1/60 是沒有意義的,因為螢屏無法更新得比這更快,而且計時器無論如何只能精確到大約 1/50 秒。)
每次updateTimer觸發,計算自開始時間以來經過的秒數并將其顯示到螢屏上:
let seconds = Date().timeIntervalSince(startTime)
Date()是當前日期和時間,精度為亞毫秒。
Date().timeIntervalSince(startTime)將為您提供自 以來的秒數startTime,再次以亞毫秒精度。
格式化并在螢屏上顯示經過的時間。您可以使用DateComponentsFormatterNumberFormatter 自己使用或構建時間字串,甚至String(format:)
uj5u.com熱心網友回復:
//
// StopWatchVC.swift
// Gem
//
// Created by Macbook 5 on 4/18/22.
//
import UIKit
class StopWatchVC:UIViewController {
var timer:Timer?
var startTime = Date()
let titleLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(titleLabel)
titleLabel.frame = CGRect(x: 0, y: 0, width: 200, height: 60)
titleLabel.center = view.center
titleLabel.textColor = .red
view.backgroundColor = .white
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
let timeInterval = Date().timeIntervalSince(startTime)
titleLabel.text = timeInterval.stringFromTimeInterval()
}
}
extension TimeInterval{
func stringFromTimeInterval() -> String {
let time = NSInteger(self)
let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)
return String(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/459931.html
