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.
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")
}
}
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.