The simplest and most common way to hide a view is like the following:
struct ContentView: View {
@State private var showText = true
var body: some View {
VStack {
Button("Toggle text") {
showText.toggle()
}
if showText {
Text("Hello World!")
}
}
}
}
This removes the Text
view from the hierarchy when showText
equals false
. If you wish to have an option to preserve the space or want it as a modifier, see below.
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 extension below is also available on GitHub here if you want to use Swift Packages: GeorgeElsham/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
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…