1

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!

pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • 2
    And where is everything concerning `doIWantThisViewToShow`? – Asperi Oct 29 '20 at 18:22
  • I tried to keep the mentioned code as short as possible, but yes I forgot to mention `@State var doIWantThisViewToShow`. –  Oct 30 '20 at 07:01

2 Answers2

3

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()
                }
            }
        }
    }
    
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
pawello2222
  • 46,897
  • 22
  • 145
  • 209
2

In addition to the pawello's answer, you can hide it like:

MyView()
  .hidden($doIWantThisViewToShow)

with this simple extension

extension View {
    @ViewBuilder func hidden(_ shouldHide: Bool) -> some View {
        switch shouldHide {
        case true: self.hidden()
        case false: self
        }
    }
}
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278