我嘗試了幾種不同的方法來在 Xcode SwiftUI 中的三個不同應用程式中運行計時器(onRecieve 和 Scheduled),但還沒有看到計時器在模擬器中作業。我按照以下視頻中的說明進行演示:
https://www.youtube.com/watch?v=y68YmyTB7JU
我不確定 Xcode 是否有需要修改的設定以在我的筆記本電腦上的模擬器中啟用計時器,或者我是否缺少更新版本的 Xcode/SwiftUI 所需的內容。不過,截至發帖時,該視頻僅發布了大約 6 個月。
先感謝您!
內容視圖:
import SwiftUI
struct ContentView: View {
@ObservedObject var stopWatchManager = StopWatchManager()
var body: some View {
VStack {
Text(String(format: "%.1f", stopWatchManager.secondsElapsed))
.font(.system(size: 50))
.foregroundColor(.yellow)
.padding(.top, 200)
.padding(.bottom, 100)
.padding(.trailing, 100)
.padding(.leading, 100)
if stopWatchManager.mode == .stopped{
Button(action: {self.stopWatchManager.start()}){
TimerButton(label: "Start", buttonColor: .green, textColor: .black)
}
}
if stopWatchManager.mode == .running{
Button(action: {self.stopWatchManager.pause()}){
TimerButton(label: "Pause", buttonColor: .green, textColor: .black)
}
}
if stopWatchManager.mode == .paused{
Button(action: {self.stopWatchManager.start()}){
TimerButton(label: "Start", buttonColor: .green, textColor: .black)
}
Button(action: {self.stopWatchManager.stop()}){
TimerButton(label: "Stop", buttonColor: .red, textColor: .black)
}
.padding(.top, 30)
}
Spacer()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct TimerButton: View {
let label: String
let buttonColor: Color
let textColor: Color
var body: some View {
Text(label)
.foregroundColor(textColor)
.padding(.vertical, 20)
.padding(.horizontal, 90)
.background(buttonColor)
.cornerRadius(10)
}
}
秒表管理器:
import Foundation
import SwiftUI
class StopWatchManager: ObservableObject{
enum stopWatchMode {
case running
case stopped
case paused
}
@Published var mode: stopWatchMode = .stopped
@Published var secondsElapsed = 0
var timer = Timer()
func start() {
mode = .running
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {
timer in self.secondsElapsed = 1
}
}
func pause() {
timer.invalidate()
mode = .paused
}
func stop() {
timer.invalidate()
secondsElapsed = 0
mode = .stopped
}
}
uj5u.com熱心網友回復:
這是一個難以識別的偷偷摸摸的錯誤。
在您的代碼中,您已定義elapsedSeconds為:
@Published var secondsElapsed = 0
Swift 進行型別推斷來推斷這secondsElapsed是一個Inthere。當您使用String(format: "%.1f"...)它時,它需要一個Double(浮點數)并且不會使用Int.
在視頻代碼中,您會看到它secondsElapsed被定義為:
@Published var secondsElapsed = 0.0
Swift 推斷這是一個Double——如果你做出那個改變,一切都會按預期進行。
PS:您可以考慮將 Timer 與 Combine (例如Timer.publish)一起使用,以獲得更以 SwiftUI 為中心的做事方式。查看檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/399419.html
