Dynamically hiding view in SwiftUI

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

    For whoever needs it in the future, I created a ViewModifier which takes a Binding<Bool> as parameter so you can bind a boolean value to show and hide the view declaratively by just setting your showDatePicker: Bool variable.

    All code snippets require import SwiftUI.

    The ViewModifier:

    struct Show: ViewModifier {
        @Binding var isVisible: Bool
    
        @ViewBuilder
        func body(content: Content) -> some View {
            if isVisible {
                content
            } else {
                content.hidden()
            }
        }
    }
    

    The function:

    extension View {
        func show(isVisible: Binding<Bool>) -> some View {
            ModifiedContent(content: self, modifier: Show(isVisible: isVisible))
        }
    }
    

    And you can use it like this:

    var datePicker = DatePicker($datePickerDate)
                         .show(isVisible: $showDatePicker)
    
    0 讨论(0)
提交回复
热议问题