【问题标题】:SwiftUI: Animation Inside NavigationViewSwiftUI:NavigationView 内的动画
【发布时间】:2021-06-12 23:28:00
【问题描述】:

我正在尝试在 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 会影响矩形动画? 谢谢!

【问题讨论】:

    标签: ios swiftui ios-animations


    【解决方案1】:

    在 NavigationView 中视图框架为零时,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 来回答...也许这是一个错误,也许是一个实现细节。

    【讨论】:

    • 这很烦人 - NavigationView 中的任何内容都会随着内容的帧变化(又名视图)进行动画处理......任何地方都应该添加“自行车”(
    • @Asperi,我无法让它与 main.async 一起使用 - 还有其他技巧吗?在 NavigationView 中时,我的视图仍会从屏幕一侧显示动画
    猜你喜欢
    • 2021-02-10
    • 2020-01-25
    • 2021-05-29
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多