SwiftUI:无法在 MainView 中将 DetailView 转换为 ZStack 才能工作 [英] SwiftUI: Can't get the transition of a DetailView to a ZStack in the MainView to work
问题描述
我在任何地方都找不到答案,希望你们中的一位能帮助我.
I can't find the answer to this anywhere, hopefully one of you can help me out.
我有一个包含一些内容的 MainView.按下一个按钮,我想打开一个 DetailView.我正在使用 ZStack 将 DetailView 分层在顶部,填充屏幕.
I have a MainView with some content. And with the press of a button I want to open a DetailView. I am using a ZStack to layer the DetailView on the top, filling the screen.
但是使用以下代码我无法让它工作.DetailView 在插入时没有过渡,并在移除时停止.我试过手动设置 zIndex 和不设置 zIndex 以及自定义 assymetricalTransition.无法让它发挥作用.任何解决方案?
But with the following code I can't get it to work. The DetailView does not have a transition when it inserts and it stops at removal. I have tried with and without setting the zIndex manually, and a custom assymetricalTransition. Couldn't get that to work. Any solutions?
//MainView
@State var showDetail: Bool = false
var body: some View {
ZStack {
VStack {
Text("Hello MainWorld")
Button(action: {
withAnimation(.spring()) {
self.showDetail.toggle()
}
}) {
Text("Show detail")
}
}
if showDetail {
ContentDetail(showDetail: $showDetail)
.transition(.move(edge: .bottom))
}
}
.edgesIgnoringSafeArea(.all)
}
这是DetailView:
And here is the DetailView:
//DetailView
@Binding var showDetail: Bool
var body: some View {
VStack (spacing: 25) {
Text("Hello, DetailWorld!")
Button(action: { withAnimation(.spring()) {
self.showDetail.toggle()
}
}) {
Text("Close")
}
.padding(.bottom, 50)
}
.frame(width: UIScreen.main.bounds.width,
height: UIScreen.main.bounds.height)
.background(Color.yellow)
.edgesIgnoringSafeArea(.all)
}
这段代码的结果是这样的:
The result of this code is this:
我正在运行 Xcode 11.4.1,所以隐式动画似乎也不起作用.真的卡在这里,希望你们中的一位能帮助我!谢谢:)
I'm running Xcode 11.4.1 so implicit animations doesn't seem to work either. Really stuck here, hope one of you can help me out! Thanks :)
推荐答案
这里有一个解决方案.使用 Xcode 11.4/iOS 13.4 测试.
Here is a solution. Tested with Xcode 11.4 / iOS 13.4.
struct MainView: View {
@State var showDetail: Bool = false
var body: some View {
ZStack {
Color.clear // extend ZStack to all area
VStack {
Text("Hello MainWorld")
Button(action: {
self.showDetail.toggle()
}) {
Text("Show detail")
}
}
if showDetail {
DetailView(showDetail: $showDetail)
.transition(AnyTransition.move(edge: .bottom))
}
}
.animation(Animation.spring()) // one animation to transitions
.edgesIgnoringSafeArea(.all)
}
}
struct DetailView: View {
@Binding var showDetail: Bool
var body: some View {
VStack (spacing: 25) {
Text("Hello, DetailWorld!")
Button(action: {
self.showDetail.toggle()
}) {
Text("Close")
}
.padding(.bottom, 50)
}
.frame(maxWidth: .infinity, maxHeight: .infinity) // fill in container
.background(Color.yellow)
}
}
这篇关于SwiftUI:无法在 MainView 中将 DetailView 转换为 ZStack 才能工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!