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以及自定义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屋!