Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Setting View visibility based on a property value?

Tags:

swiftui

When defining a view hierarchy using SwiftUI, is it possible to set the hidden() value of a View in the body of the definition?

For example:

var body: some View {
     VStack(alignment: .leading) {
          Text(self.name)
          .font(.headline)
          .hidden()
     }
}

would hide the Text object, but I would like to use a boolean property to toggle visibility.

There is a way to do this using a ternary operator and the opacity value of the view, but I was hoping for a less clever solution.

Thanks!

like image 759
Gene Z. Ragan Avatar asked Oct 07 '19 20:10

Gene Z. Ragan


1 Answers

If you don't want to use the opacity modifier this way:

struct ContentView: View {
    @State private var showText = true

    var body: some View {
         VStack(alignment: .leading) {
              Text("Hello world")
                .font(.headline)
                .opacity(showText ? 1 : 0)
         }
    }
}

you can decide to completely remove the view conditionally:

struct ContentView: View {
    @State private var showText = true

    var body: some View {
         VStack(alignment: .leading) {
            if showText {
                Text("Hello world")
                    .font(.headline)
            }
         }
    }
}

Consider that both ways are widely used in SwiftUI. For your specific case I'd honestly use the opacity modifier, but even the removal is fine.

like image 152
matteopuc Avatar answered Dec 14 '22 22:12

matteopuc