Pass start date for DatePicker from another view

I have a view (ItemRow), that invokes another view (EditView) passing a struct that contains a date. I invoke EditView like this:

NavigationLink(destination: EditView(item: item))

In EditView, I have the property ‘item’ and a State variable to use in DatePicker:

var item: Periodical
@State private var expirationDate = item.expirationDate

This gives me an error "Cannot use instance member ‘item’ within property initializer.

How can I get the expiration date from the struct into the State variable so it shows up as the default date?

Assuming that you are using expirationDate as the Binding in the picker, you could use onAppear and set it there.

.onAppear {
    expirationDate = item.expirationDate
}

You would have to declare your expirationDate as

@State private var expirationDate = Date()

which you would immediately overwrite via onAppear()

Yes! That did it. Thank you.

1 Like