更新属性观察者 didSet 在弹出框被解除时有机会做一些工作。尝试这个:
struct UpdateOnDismissView: View {
@EnvironmentObject var context : LaunchContext
var body: some View {
VStack {
Text("\(context.launch)").padding()
Button("Set Launch Date", action: { context.show.toggle() })
.padding()
.popover(isPresented: $context.show, content: { panel })
}
}
var panel : some View {
VStack {
Button("Done", action: { context.show.toggle() })
DatePicker("Launch", selection: Binding(get: {
context.launch
}, set: { newValue in
context.launch = newValue
}), displayedComponents: [.date, .hourAndMinute])
}
.padding()
.onDisappear(perform: {
print("Popover disappearing")
})
}
}
struct UpdateOnDismissView_Previews: PreviewProvider {
static var previews: some View {
UpdateOnDismissView().environmentObject(LaunchContext())
}
}
class LaunchContext : ObservableObject {
@Published var launch : Date = Date()
@Published var show : Bool = false { didSet {
if !show && launch < Date() {
sendLaunchToServer()
} else {
print("Dismissed")
}
}}
func sendLaunchToServer() {
print("Sending date \(launch)")
}
}
什么时候应该使用属性观察器?