SwiftUI tvOS 按钮动画 - 如何停止 y 轴移动

SwiftUI tvOS button animation - how to stop y axis movement

当文本是按钮的一部分时(在 tvOS 14.7 上),这个简单的 x 偏移动画代码会导致文本也在 y 轴上移动

struct Animate: View
{
    @State var scrollText: Bool = false
    
    var body: some View {
        Button(action: {}, label: {
            Text("This is My Text !")
                .offset(x: scrollText ? 0 : 200, y: 0)
                .animation(Animation.linear(duration: 1).repeatForever(autoreverses: true))
                .onAppear {
                  self.scrollText.toggle()
                }
        })
    }
}

在此处查看动画行为: marquee gone wrong

如何停止 y 轴移动?

您始终需要为动画设置 value。否则,SwiftUI 将对所有更改进行动画处理,包括不需要的定位。

struct Animate: View {
    @State var scrollText: Bool = false
    
    var body: some View {
        Button(action: {}) {
            Text("This is My Text !")
                .offset(x: scrollText ? 0 : 200, y: 0)
                .animation(Animation.linear(duration: 1).repeatForever(autoreverses: true), value: scrollText) /// only update animation when `scrollText` changes
                .onAppear {
//                    DispatchQueue.main.async { /// you might also need this
                        self.scrollText.toggle()
//                    }
                }
        }
    }
}

结果:

This video might also be helpful