如何在 SwiftUI 中即时更新视图? [英] How to make the View update instant in SwiftUI?

查看:105
本文介绍了如何在 SwiftUI 中即时更新视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Text 用作具有不同数组值的计时器.它以 timerIntervalSinceNow 显示.

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

问题是当它达到零时它应该显示零,但在再次点击屏幕之前不会发生这种情况.如果我不点击它,它会继续上升,因为它是 timeIntervalSinceNow,但是当我点击它时,它会切换到 0 secText.

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.

有什么方法可以让 SwiftUI 在不点击的情况下自行执行此操作吗?

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)
}

推荐答案

问题在于 exerciseTime[value] 永远不会改变,所以视图不会重绘.

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

即使 exerciseTime[value].timeIntervalSinceNow 可能不同,实际的 exerciseTime[value] 保持不变.

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

我建议您使用带有 ObservableObjectTimer 代替:

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)
        }
    }
}

这篇关于如何在 SwiftUI 中即时更新视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆