iosswiftviewswiftuihide

Hide/show views on button tap - SwiftUI


I have a view, created separately in another file, that I want to show and hide conditionally when a button is pressed.

I tried several techniques like changing the opacity or offset depending on a boolean, but it doesn't work once I put the view in another SwiftUI file.

My project looks like this:

In ContentView.swift, inside var body: some View

@State var doIWantThisViewToShow: Bool = false

MyView()
        .padding()
        .opacity(doIWantThisViewToShow ? 1 : 0)

In MyView.swift

struct MyView: View {
    var body: some View {
        Text("Text")
    }
}

Thanks in advance!


Solution

  • You can show/hide your view in different ways. Here are some that may help you:

    1. opacity (the hidden view stays in the view hierarchy, ie. other views keep their positions):

      struct ContentView: View {
          @State var doIWantThisViewToShow: Bool = false
      
          var body: some View {
              VStack {
                  Button("Show/Hide MyView") {
                      doIWantThisViewToShow.toggle()
                  }
                  MyView()
                      .padding()
                      .opacity(doIWantThisViewToShow ? 1 : 0)
              }
          }
      }
      
    2. if-statement (the hidden view is removed from the view hierarchy, ie. other views positions will be rearranged):

      struct ContentView: View {
          @State var doIWantThisViewToShow: Bool = false
      
          var body: some View {
              VStack {
                  Button("Show/Hide MyView") {
                      doIWantThisViewToShow.toggle()
                  }
                  if doIWantThisViewToShow {
                      MyView()
                          .padding()
                  }
              }
          }
      }