ios - SwiftUI 动画/转换覆盖 View 不起作用

标签 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)
)

出于某种原因,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))
            }
        }
    }
}

关于ios - SwiftUI 动画/转换覆盖 View 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58132269/

相关文章:

ios - 在安装时将初始内容添加到应用程序中

ios - Swift:按名称(字符串)按字母顺序将对象数组映射到新数组中的单独字母集合中

ios - 如何处理 TextField 的 shouldChangeCharactersIn(如果它位于 TabelViewControler 的自定义单元格中)

ios - SwiftUI 动画 : How to stagger repeating animation with delay

ios - phonegap iOS文件上传使用输入(文件)

ios - UIPageViewController的进度

ios - 如何从模型中的函数接收 View 中的异步结果?

swift - 在 SwiftUI NaviagationLink 中创建 ManagedObject

swiftui - 如何查看 SwiftUI 可以提供的其他字体选项作为自定义字体?

xcode - SwiftUI 包装的 SearchBar 无法关闭键盘