SwiftUI:导航视图中的动画

人气:1,084 发布:2022-10-16 标签: ios swiftui ios-animations

问题描述

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

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中的图框为零时,onOuar被调用得太早,因此应用动画以从零更改为值。

以下是有效的解决方法。使用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回答...可能是错误,也可能是实现细节。

535