在SwiftUI中使用计时器更新文本可以通过以下步骤实现:
import SwiftUI
import Combine
ObservableObject
的类,用于存储计时器的状态和更新文本:class TimerManager: ObservableObject {
@Published var currentTime: String = ""
private var timer: Timer?
init() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
self.currentTime = formatter.string(from: Date())
}
}
}
@ObservedObject
属性包装计时器管理器,并在文本视图中显示当前时间:struct ContentView: View {
@ObservedObject var timerManager = TimerManager()
var body: some View {
Text(timerManager.currentTime)
.font(.largeTitle)
.padding()
}
}
SceneDelegate.swift
文件中,将视图添加到窗口的根视图中:func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()
}
}
这样,每秒钟计时器都会更新一次,并在视图中显示当前时间。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)
请注意,以上答案仅供参考,具体实现方式可能因个人需求和环境而异。
领取专属 10元无门槛券
手把手带您无忧上云