Dynamically hiding view in SwiftUI

前端 未结 7 1291
-上瘾入骨i
-上瘾入骨i 2020-12-24 10:41

I\'m trying to conditionally hide a DatePicker in SwiftUI. However, I\'m having any issue with mismatched types:

var datePicker = DatePicker($da         


        
7条回答
  •  一个人的身影
    2020-12-24 11:11

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

提交回复
热议问题