ios - SwiftUI:NavigationView 内的动画

标签 ios swiftui ios-animations

我正在尝试在 SwiftUI 中创建一个简单的动画。它基本上是一个改变其框架的矩形,同时保持在父 View 的中心。

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                Text("Text")
                ZStack {
                    Color.blue
                    SquareAnimation().frame(width: 200, height: 200, alignment: .center)
                }
                Text("Text")
            }
        }
    }
}

struct SquareAnimation: View {
    var currentRect = CGRect(x: 0, y: 0, width: 50, height: 50)
    var finalRect = CGRect(x: 0, y: 0, width: 100, height: 100)
    
    private let animation = Animation.easeInOut(duration: 1).repeatForever(autoreverses: true)
    
    @State var animate = false
    
    var body: some View {
        ZStack() {
            Color.clear
            Rectangle()
                .frame(width: animate ? finalRect.width: currentRect.width, height: animate ? finalRect.height: currentRect.height, alignment: .center)
                .animation(animation, value: animate)
                .onAppear() {
                    animate = true
                }
        }
        
    }
} 
问题是,如果 NavigationView,黑色矩形不会停留在中心。用来。
我也使用了显式动画但无济于事。为什么 NavigationView影响矩形动画?

最佳答案

当在 NavigationView 中 View 框架为零时,onAppear 被调用得太早,因此应用动画从零变为值。
这是有效的解决方法。使用 Xcode 12.4/iOS 14.4 测试

var body: some View {
    ZStack() {
        Color.clear
        Rectangle()
            .frame(width: animate ? finalRect.width: currentRect.width, height: animate ? finalRect.height: currentRect.height, alignment: .center)
            .animation(animation, value: animate)
            .onAppear {
                DispatchQueue.main.async {   
                   // << postpone till end of views construction !!
                    animate = true
                }
            }
    }
}
注意:几乎所有为什么问题都只能由 Apple 来回答......也许这是一个错误,也许是一个实现细节。

关于ios - SwiftUI:NavigationView 内的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66642367/

相关文章:

swift - Xcode 11 测试版 5 : "' subscript(_: )' is deprecated: See Release Notes for migration path. "

iphone - Http直播到iphone

iphone - 推送新的 UIVIew 时禁用所有交互 UIViewcontroler

ios - 从网站解析 XML 文件到 UITextView

swift - 与 NavigationView 结合添加滚动

swiftui - iOS 14无效的框架尺寸(负数或非有限数)

iOS如何在屏幕外启动图像并将其动画化到屏幕上

ScrollView 内的 SwiftUI 动画错误

ios - 在常见情况下,什么时候使用 Core Animation 而不是 UIView 动画是合适的

ios - SKStoreProductViewController SKStoreProductViewControllerDelegate ,没有错误处理?