SwiftUI 对叠加视图进行动画处理/过渡不起作用



我正在尝试做这样的事情:

VStack { 
content()
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.overlay(
MyView()
.transition(.asymmetric(insertion: .move(edge: .top), removal: .opacity))
.animation(.easeInOut)
)

由于某种原因,MyView没有动画。有人对此有解决方案吗?

在 SwiftUI 中,您可以告诉应用您希望 UI 在给定状态下的外观。然后,如果您的状态发生变化,SwiftUI 会神奇地从显示状态 1 过渡到显示状态 2。

在这种情况下,您已经告诉 SwiftUI,您想要一个顶部覆盖着 MyView 的 VStack,并且如果有动画,您希望它具有这样那样的过渡和动画样式。但是,由于您只提供了单个应用状态,因此没有两个状态可以在两者之间进行动画处理。

下面的代码示例应该说明我假设您正在尝试执行的操作:

struct ContentView: View {
// We have two states - the border rectangle is shown, or not shown
// @State allows SwiftUI to know to redraw anything that changes when this variable changes
@State private var showingOverlay = false
var body: some View {
// We lay our root view down first, and the border rectangle on top using ZStack
ZStack {
// VSTack likes to shrink down as small as it's content allows
VStack {
Text("Hello World")
}
// .background() is kind of an implicit ZStack, which lets other content
//    flow around the VStack like it had the Rectangle's dimensions
.background(
Rectangle()
.fill(Color.gray)
.frame(width: 300, height: 300)
)
// When the VStack appears (when your app launches), set the showingOverlay variable to true
// Two seconds later, set it back to false
.onAppear {
self.showingOverlay.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.showingOverlay.toggle()
}
}
// We only show this Rectangle if the showingOverlay variable is true
// Since we are transitioning from not showing, to showing, to not showing, SwiftUI will animate
if showingOverlay {
Rectangle()
.stroke(Color.blue, lineWidth: 5)
.frame(width: 300, height: 300)
.transition(.asymmetric(insertion: .move(edge: .top), removal: .opacity))
.animation(.easeInOut(duration: 1))
}
}
}
}

最新更新