【问题标题】:SwiftUI tvOS button animation - how to stop y axis movementSwiftUI tvOS 按钮动画 - 如何停止 y 轴移动
【发布时间】:2021-11-06 15:41:11
【问题描述】:

当文本是按钮的一部分时(在 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 轴运动?

【问题讨论】:

    标签: animation button swiftui marquee


    【解决方案1】:

    您始终需要为动画设置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

    【讨论】:

    • 关于未设置的值,我看不出与我的原始代码有任何区别,但在我取消注释后:“DispatchQueue.main.async”行 - 它工作,完美!,谢谢分配跨度>
    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 2017-12-22
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    相关资源
    最近更新 更多