我想知道是否可以在 iOS 实时活动中创建一个简单的秒数计数器,该计数器将从提供的 unix 时间戳开始并相对于当前日期。例如:“00:01”、“00:02”、...
我知道如何创建倒计时器,如下所示:
Text(Date(timeIntervalSinceNow: 60), style: .timer)
但是我还没有成功地让它以相反的方式工作,或者找到很多与此相关的信息。
Text(
Date(
timeIntervalSinceNow: Double(context.state.startedAt) - Date().timeIntervalSince1970
),
style: .timer
)
Text(Date(timeIntervalSinceNow: Double(Date().timeIntervalSince(Date())) - Double(Date().timeIntervalSince(Date() - 1))
),
style: .timer)
Text(context.attributes.recordingStart, style: .timer)
我在以下现场活动的实现中使用了它:
struct RecordingInProgressAttributes: ActivityAttributes {
struct ContentState: Codable, Hashable {
// Dynamic stateful properties about your activity go here!
}
// Fixed non-changing properties about your activity go here!
let recordingStart: Date
}
请注意,recordingStart 这里是日期,而不是时间戳。
struct RecordingInProgressLiveActivity: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: RecordingInProgressAttributes.self) { context in
Text(context.attributes.recordingStart, style: .timer)
} dynamicIsland: { context in
/// other stuff, like dynamic island
}
}
}
//
// SampleStopWatch.swift
//
import UIKit
class SampleStopWatch:UIViewController {
var timer:Timer?
var startTime = Date()
override func viewDidLoad() {
super.viewDidLoad()
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)
let titleLabel = timeInterval.stringFromTimeInterval() // show this text on label
//labeltoShow.text = titleLabel
print("title label " + titleLabel)
}
}
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)
}
}