SwiftUI条件视图将不进行动画/过渡 [英] SwiftUI conditional view will not animate/transition
问题描述
我正在尝试使用 .transition()
在视图上进行动画/过渡.我在此处使用了类似的代码并将 .transition()
放入两个条件视图.
I’m trying to get my views to animate/transition using .transition()
on views. I use similar code from here and put .transition()
to both conditional views.
struct Base: View {
@State private var isSignedIn = false
var body: some View {
Group {
if(isSignedIn){
Home().transition(.slide)
}else{
AuthSignin(isSignedIn: self.$isSignedIn).transition(.slide)
}
}
}
}
struct AuthSignin: View {
@Binding var isSignedIn: Bool
var body: some View {
VStack {
Button(action: {
self.isSignedIn = true
}) {
Text("Sign In")
.bold()
.frame(minWidth: CGFloat(0), maxWidth: .infinity)
.padding()
.background(Color.blue)
.foregroundColor(Color.white)
.cornerRadius(CGFloat(10))
}.padding()
}
}
}
但是,每当我单击登录"按钮(带有或不带有 .transition()
)时,该应用都会冻结一秒钟,然后冻结 Home()代码>视图将突然出现而没有任何动画/过渡.我也曾尝试将
self.isSignedIn = true
包装在 withAnimation
中,但仍然无法正常工作.有什么想法或有更好的方法吗?
However, whenever I click on the "Sign In" button (with or without .transition()
), the app will freeze for a second and then the Home()
view will suddenly appear without any animation/transition. I've also tried to wrap self.isSignedIn = true
in withAnimation
but it still won't work. Any ideas or is there a better way to do this?
推荐答案
将您的 .transition
放置在要切换的视图的容器中,而不是每个条件视图.这是我完成的一些代码的一个简单示例(有效).
Place your .transition
on the container of the views that will switch, not each conditional view. Here's a trivial example from some code I have done (which works).
在需要有条件转换的主视图中:
In the main View that needs to transition conditionally:
import SwiftUI
struct AppWrapperView: View {
@State var showFirstRun:Bool = true
var body: some View {
ZStack {
if (showFirstRun) {
FirstRunView(showFirstRun: $showFirstRun)
} else {
Text("Some other view")
}
}
.transition(.slide)
}
}
然后,在视图中触发条件变化的某处:
Then, somewhere in the view that triggers the change in condition:
import SwiftUI
struct FirstRunView: View {
@Binding var showFirstRun:Bool
var body: some View {
Button(action: {
withAnimation {
self.showFirstRun = false
}
}) {
Text("Done")
}
}
}
这篇关于SwiftUI条件视图将不进行动画/过渡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!