0

I have a DatePicker such as:

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

enter image description here

enter image description here

As opposed to calling sendDateTimeToServer() every time dateTime changes I want to wait until the fullscreen (2nd image) DatePicker has collapsed, is there an event? Open to other suggestions too!

Thanks,

1 Answer 1

1

Update Property observers didSet gives a chance do some work when the popover is dismissed. Try this:

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

When should you use property observers?

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, .onDisappear isn't being called.
Could you share more about the life-cycle of the date picker? Maybe post the entire struct or at least the body?
Seems like onDisappear would only get called when the entire DatePicker were removed from the view hierarchy -- not just the popup window the OP referred to. FWIW, I looked into this and couldn't find a good solution.
The code sample has been updated to include the entire view. Hopefully the expanded example is useful.
Thanks Helperbug, as jnpdx states I'm looking for the event that relates to the popup window.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.