Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

ios - How to make the View update instant in SwiftUI?

I have a Text that acts as a timer with different values of my array. And it displays with timerIntervalSinceNow.

The problem is when it reaches zero it should show zero to but that does not happen before clicking again on the screen. If I do not click on it it keeps going up since it is timeIntervalSinceNow, but when I click it switches to the Text with 0 sec.

Any way on telling SwiftUI to do this by itself without clicking?

if(exerciseTime[value].timeIntervalSinceNow > 0) {
    Text(exerciseTime[value], style:.relative).foregroundColor(.white).font(.largeTitle).padding(.top, 30)                                   
} else {
    Text("0 sec").foregroundColor(.white).font(.largeTitle).padding(.top, 30)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that exerciseTime[value] never changes, so the view is not redrawn.

Even though exerciseTime[value].timeIntervalSinceNow might be different, the actual exerciseTime[value] remains constant.

I recommend you use a Timer with an ObservableObject instead:

import Combine
import SwiftUI

class TimerViewModel: ObservableObject {
    private var timer: AnyCancellable?

    @Published var currentDate = Date()

    func start(endDate: Date) {
        timer = Timer.publish(every: 1.0, on: .main, in: .default)
            .autoconnect()
            .sink { [weak self] in
                guard let self = self else { return }
                self.currentDate = $0
                if self.currentDate >= endDate {
                    self.timer = nil
                }
            }
    }
}

and use it in your view:

struct TestView: View {
    @State private var exerciseTime = Calendar.current.date(byAdding: .second, value: 15, to: Date())!
    @StateObject private var timer = TimerViewModel()

    var body: some View {
        Group {
            if timer.currentDate < exerciseTime {
                Text(exerciseTime, style: .relative)
            } else {
                Text("0 sec")
            }
        }
        .foregroundColor(.white)
        .font(.largeTitle)
        .padding(.top, 30)
        .onAppear {
            timer.start(endDate: exerciseTime)
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...