0

this simple code of x offset animation causes a text to move also on y axis when the text is part of a button (on tvOS 14.7)

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()
                }
        })
    }
}

see the animation behavior here: marquee gone wrong

How can i stop the y axis movement ?

Shaybc
  • 2,628
  • 29
  • 43

1 Answers1

1

You always need to set a value for your animations. Otherwise, SwiftUI will animate all changes, include unwanted positioning.

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()
//                    }
                }
        }
    }
}

Result:

No weird position animation

This video might also be helpful

aheze
  • 24,434
  • 8
  • 68
  • 125
  • 1
    I couldn't see any difference from my original code, regarding unset values, but after i un-remarked: "DispatchQueue.main.async" lines - it worked, perfect!, thanks allot – Shaybc Sep 10 '21 at 06:37