I\'m trying to conditionally hide a DatePicker in SwiftUI. However, I\'m having any issue with mismatched types:
var datePicker = DatePicker($da
You can set the alpha instead, this will preserve the layout space of the view too and does not force you to add dummy views like the other answers:
struct ContentView : View {
@State var showDatePicker = true
@State var datePickerDate: Date = Date()
var body: some View {
VStack {
DatePicker($datePickerDate)
.opacity(showDatePicker ? 1 : 0)
}
}
}
I hope hidden modifier gets argument later.
Also, you can implement a custom function to get the visibility state as an argument:
extension View {
@ViewBuilder func hidden(_ shouldHide: Bool) -> some View {
switch shouldHide {
case true: self.hidden()
case false: self
}
}
}
Now just pas the bool to the modifier:
DatePicker($datePickerDate)
.hidden(showDatePicker)
Note that unlike the original behavior of the hidden modifier, both of these methods preserve the frame of the hiding view.