GIF of Entire Screen Refreshing
我目前正在学习联合收割机和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
}
}
答案 0 :(得分:1)
如果您只想刷新身体的一部分,则将该部分分成专用的子视图,例如:
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 !!
}
}
}