首页 > 解决方案 > SwiftUI tvOS 按钮动画 - 如何停止 y 轴移动

问题描述

当文本是按钮的一部分时(在 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()
                }
        })
    }
}

在此处查看动画行为: 选框出错

如何停止 y 轴运动?

标签: animationbuttonswiftuimarquee

解决方案


你总是需要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()
//                    }
                }
        }
    }
}

结果:

没有奇怪的位置动画

这个视频也可能有帮助


推荐阅读