SwiftUI 旋转动画有意想不到的翻译

Rob*_*arg 5 ios swiftui

我正在尝试使用标准且一致的在线教程在 SwiftUI 中为旋转的“忙碌”图像制作动画View。图像是正方形的,应该均匀缩放,并且永远旋转。

我可以使用以下代码获得旋转图像,但是我看到了意外的翻译。当用作初始视图时,NavigationView图像动画过程中从左上角移动到屏幕中央。当用作第三个屏幕时,NavigationView图像大致从屏幕中心开始,并在动画过程中垂直向下移动大约其高度的一半。删除导航栏和后退按钮将垂直偏移总体减少到约 20 像素。这很有趣。

另外有趣的是,在这两种情况下,背景都准确地保持在我期望的位置,即屏幕的中央。 autoreverses行为符合预期,并且anchor旋转效果似乎没有效果。

目的是在屏幕上添加额外的控件(文本、下一步按钮等),但目前我对保留在一个位置的动画感到满意。

我究竟做错了什么?任何帮助表示赞赏!

说明问题的图片代码:

@State private var isAnimating = false

var body: some View {
    VStack{
        Spacer()
        Image("FilmCircle")
            .resizable()
            .scaledToFit()
            .frame(width: 100, height: 100)
            .rotationEffect(Angle(degrees: isAnimating ? 360 : 0), anchor: .center)
            .animation(Animation.linear(duration: 2)
                .repeatForever(autoreverses: false))
            .onAppear {
                self.isAnimating = true
            }
            .background(Color.red)
        Spacer()
    }
}
Run Code Online (Sandbox Code Playgroud)

Nam*_*mar 4

在声明动画之前声明 .backgound(Color.red) ,以便它也可以为背景设置动画。

对于使用导航视图时的问题,请参阅代码:-

    VStack{
    Spacer()
    Image("FilmCircle")
        .resizable()
        .scaledToFit()
        .background(Color.red)
        .frame(width: 100, height: 100)
        .rotationEffect(Angle(degrees: isAnimating ? 360 : 0), anchor: .center)
        .onAppear {
             DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                           withAnimation(.linear(duration: 2).repeatForever(autoreverses: false)) {
                               isAnimating = true
                           }
                       }
        }
        Spacer()
    }
Run Code Online (Sandbox Code Playgroud)

希望您觉得这有帮助。