0

I'd like to perform an action to hide elements on my screen when a button is tapped using SwiftUI.

So for example, let's say I have 2 images, a text, and a button on my screen.

If I tap the button I want the other elements to animate off-screen. Tap the button again and they animate back onto the screen.

Each element is created in their own View which is in its own file. Is there a way to access a View from another View?

Here's an example:

struct buttonView : View {

    @State private var isShowingImageView = false

    @Binding var myImage: ImageView

    var body: some View {
        Button(action: {
                    self.isShowingImageView.toggle()
                }) {
                    HStack(spacing: 18) {
                        Image("button-icon")
                        Text("Press Me")
                    }

                }

            if isShowingImageView {
                myImage.hidden()
            }
    }

}

My image is created in its own struct / View and when I press the button I want to hide that image.

Right now it's not hiding it, just the view my button is in animates a little.

2 Answers 2

2

As Sam has stated already you could use a combination of @State and @Binding.

struct ContentView: View {

    @State private var show = true

    var body: some View {
        VStack {
            View1(show: $show)
            View2(show: $show)
        }
    }
}

struct View1: View {

    @Binding var show: Bool

    var body: some View {
        VStack {
            if show {
                Text("Text1")
            }

            Text("Text2")
        }
    }
}

struct View2: View {

    @Binding var show: Bool

    var body: some View {
        VStack {
            Text("Text3")

            if show {
                Text("Text4")
            }

            Button(action: {
                self.show.toggle()
            }) {
                Text("Toogle show")
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!
1

From your master/root view, you can create @State variables that you pass into the subviews as @Binding variables.

I can't give you more specifics without seeing your code, but it is possible.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.