I'm trying to conditionally hide a DatePicker
in SwiftUI. However, I'm having any issue with mismatched types:
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
In this case, datePicker
is a DatePicker<EmptyView>
type but datePicker.hidden()
is a _ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>
. So I cannot assign datePicker.hidden()
to datePicker
. I've tried variations of this and can't seem to find a way that works. Any ideas?
UPDATE
You can unwrap the _ModifiedContent
type to get the underlying type using it's content
property. However, this doesn't solve the underlying issue. The content
property appears to just be the original, unmodified date picker.
Rather than dynamically setting a variable and using it in my view, I found that I was able to hide or show the date picker this way:
struct ContentView : View {
@State var showDatePicker = true
@State var datePickerDate: Date = Date()
var body: some View {
VStack {
if self.showDatePicker {
DatePicker($datePickerDate)
} else {
DatePicker($datePickerDate).hidden()
}
}
}
}
Or, optionally, not including the date picker instead of hiding it:
struct ContentView : View {
@State var showDatePicker = true
@State var datePickerDate: Date = Date()
var body: some View {
VStack {
if self.showDatePicker {
DatePicker($datePickerDate)
}
}
}
}