我目前正在學習 swiftui 并且遇到以下問題:
我的代碼包含一個計時器,該計時器在打開應用程式時進行計數。到目前為止,這作業正常。現在我希望在應用程式關閉和重新打開時保存上一個時間,然后從那里加載并計數值。
有沒有一種簡單的方法來實作這個?
這是我的代碼:
struct TimeView: View {
@State private var timeTracker = 0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
HStack{
Text("\(timeTracker) s")
}
.onReceive(timer) { time in
self.timeTracker = 1
}
}
}
struct TimeView_Previews: PreviewProvider {
static var previews: some View {
TimeView()
}
}
uj5u.com熱心網友回復:
struct TimeView: View {
@State private var timeTracker = 0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
@AppStorage("TIME") var time: Int = 0
var body: some View {
HStack{
Text("\(timeTracker) s")
}
.onReceive(timer) { _ in timeTracker = 1 }
.onAppear(perform: { timeTracker = time })
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in time = timeTracker }
}
}
//OR
struct TimeView: View {
@AppStorage("TIME") var timeTracker: Int = 0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
HStack{
Text("\(timeTracker) s")
}
.onReceive(timer) { _ in timeTracker = 1 }
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/405330.html
標籤:
