2

全屏刷新的GIF

我目前正在学习组合和 MVVM。我的问题是当我尝试使用 timer.publish 时,最终我要创建一个停止按钮,它会导致整个屏幕刷新而不是我拥有的文本 .onReceive。

我希望有人能给我一些关于我如何错误地使用发布者和观察者的见解。

看法:

import SwiftUI
import Combine

struct ApptCardView: View {

    @ObservedObject var apptCardVM: ApptCardViewModel
    @State var currentDate = Date()
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        VStack {
            Text("\(currentDate)")
                .onReceive(timer) { input in
                    self.currentDate = input
                   }
            Picker("Seizure Type", selection: $apptCardVM.typeIndex) {
            ForEach(0..<apptCardVM.typeChoice.count) {
                Text(self.apptCardVM.typeChoice[$0])
            }
        }.pickerStyle(SegmentedPickerStyle())

        }

    }
}

查看型号:

import Foundation
import Combine


class ApptCardViewModel: ObservableObject, Identifiable {

    @Published var appt: ApptEvent
    @Published var typeChoice = ["Quick", "Long", "FullService"]
    @Published var typeIndex: Int = 0



    private var cancellables = Set<AnyCancellable>()

    init(appt: ApptEvent) {
        self.appt = appt
    }

}
4

1 回答 1

2

如果您只想刷新正文的一部分,则将该部分分成专用的子视图,例如:

struct ApptCardView: View {

    @ObservedObject var apptCardVM: ApptCardViewModel

    var body: some View {
        VStack {
            CurrentDateView()  // << here !!

            Picker("Seizure Type", selection: $apptCardVM.typeIndex) {
            ForEach(0..<apptCardVM.typeChoice.count) {
                Text(self.apptCardVM.typeChoice[$0])
            }
        }.pickerStyle(SegmentedPickerStyle())

        }

    }
}

struct CurrentDateView: View {
    @State private var currentDate = Date()
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    var body: some View {
        Text("\(currentDate)")
            .onReceive(timer) { input in
                self.currentDate = input // << refresh only own body !!
        }
    }
}
于 2020-06-01T18:08:06.457 回答