Dynamically hiding view in SwiftUI

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

    I created an extension, so you can use a modifier, like so to hide the view:

    Text("Hello World!")
        .isHidden(true)
    

    Or for complete removal:

    Text("Label")
        .isHidden(true, remove: true)
    

    The source code is available on GitHub here: George-J-E/HidingViews.


    Here is the code to create the View modifier:

    I recommend you use this code in its own file (remember to import SwiftUI):

    extension View {
        
        /// Hide or show the view based on a boolean value.
        ///
        /// Example for visibility:
        /// ```
        /// Text("Label")
        ///     .isHidden(true)
        /// ```
        ///
        /// Example for complete removal:
        /// ```
        /// Text("Label")
        ///     .isHidden(true, remove: true)
        /// ```
        ///
        /// - Parameters:
        ///   - hidden: Set to `false` to show the view. Set to `true` to hide the view.
        ///   - remove: Boolean value indicating whether or not to remove the view.
        @ViewBuilder func isHidden(_ hidden: Bool, remove: Bool = false) -> some View {
            if hidden {
                if !remove {
                    self.hidden()
                }
            } else {
                self
            }
        }
    }
    

提交回复
热议问题