[英]Hiding a SwiftUI View from another SwiftUI View
I'd like to perform an action to hide elements on my screen when a button is tapped using SwiftUI.当使用 SwiftUI 点击按钮时,我想执行一个操作来隐藏屏幕上的元素。
So for example, let's say I have 2 images, a text, and a button on my screen.例如,假设我的屏幕上有 2 个图像、一个文本和一个按钮。
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
.正如 Sam 已经说过的,您可以结合使用@State
和@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.从你的主/根视图,您可以创建@State
变量传递到子视图@Binding
变量。
I can't give you more specifics without seeing your code, but it is possible.如果没有看到您的代码,我无法为您提供更多细节,但这是可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.