为什么 NavigationView 中的动画从左上角开始? [英] Why does an animation in a NavigationView starts from the top left corner?

查看:29
本文介绍了为什么 NavigationView 中的动画从左上角开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 SwiftUI 中创建一个简单的动画,并且我希望动画从中心顶部开始并结束到屏幕中心.
但是,正如您在视频中看到的,当我使用 NavigationView 时,动画从左上角开始:

I'm trying to create a simple animation in SwiftUI and I would like the animation to start from center top and end to the center of the screen.
But, as you can see in the video, the animation starts from the top left corner when I use a NavigationView:

这是我在此示例中使用的代码:

This is the code I am using for this example:

struct ContentView: View {
    
    @State var show = false
    
    var body: some View {
        NavigationView {
            HStack {
                Text("Hello, world!")
                    .padding()
                    .background(Color.blue)
                    .offset(x: 0, y: show ? 0 : -30)
                    .animation(Animation.easeOut.delay(0.6))
                    .onAppear {
                            self.show = true
                    }
                    .navigationTitle("Why?")
            }
        }
    }
}

推荐答案

为什么 NavigationView 中的动画从左上角开始?

Why does an animation in a NavigationView starts from the top left corner?

因为隐式动画会影响所有可设置动画的属性,包括位置,在创建时为 CGPoint.zero(即左上角).

Because implicit animation affects all animatable properties, including position, which on creation time is CGPoint.zero (ie. top-left corner).

这种情况是通过将动画链接到依赖状态值来解决的,因此它仅在状态改变时激活,因此所有可动画属性不受影响.

Such cases are solved by linking animation to dependent state value, thus it activates only when state changed, so all animatable properties not affected.

这是您的情况的可能变体.使用 Xcode 12.1/iOS 14.1 测试.

Here is possible variant for your case. Tested with Xcode 12.1 / iOS 14.1.

struct ContentView: View {
    
    @State var show = false
    
    var body: some View {
        GeometryReader { gp in
            NavigationView {
                    HStack {
                         Text("Hello, world!")
                              .padding()
                              .background(Color.blue)
                              .offset(x: 0, y: show ? 0 : -gp.size.height / 2)
                              .animation(Animation.easeOut.delay(0.6), value: show)
                              .onAppear {
                                         self.show = true
                              }
                              .navigationTitle("Why?")
                    }
            }
        }
    }
}

这篇关于为什么 NavigationView 中的动画从左上角开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆