Dynamically hiding view in SwiftUI

前端 未结 7 1290
-上瘾入骨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:15

    The Simplest Way:

    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.


    A Cleaner Way (pass as an argument):

    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.

提交回复
热议问题