0

我有一个 DatePicker,例如:

DatePicker("DATE & TIME", selection: Binding(get: {
    self.dateTime
 }, set: { newValue in
    self.dateTime = newValue
    if newValue > Date() {
         sendDateTimeToServer()
    }
}), displayedComponents: [.date, .hourAndMinute])

在此处输入图像描述

在此处输入图像描述

与每次 dateTime 更改时调用 sendDateTimeToServer() 不同,我想等到全屏(第二张图像)DatePicker 折叠,有事件吗?也欢迎其他建议!

谢谢,

4

1 回答 1

1

更新属性观察者 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)")
    }
}

什么时候应该使用属性观察器?

于 2021-02-13T22:13:20.890 回答