SwiftUI 动画/转换覆盖视图不起作用

Ser*_*oca 5 ios swiftui

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

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

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

Joh*_* M. 8

在 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))
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)