I would like to animate long single line of text to display the entire text by scrolling left and right on repeat.
I tried to do this myself using the following code, but it just scrolls to the end of the text when the view is loaded. It doesn’t scroll back.
private func scrollViewForLongName(
_ name: String) -> some View {
let topID = 1
let bottomID = 29
return ScrollViewReader { proxy in
ScrollView(.horizontal, showsIndicators: false) {
HStack {
Text(name)
.id(topID)
.onAppear {
let baseAnimation = Animation.easeInOut(duration: 1)
let repeated = baseAnimation.repeatForever(autoreverses: true)
DispatchQueue.main.async {
withAnimation(repeated) {
proxy.scrollTo(bottomID)
}
}
}
Text(" ")
.id(bottomID)
}
}
}
}
2
Answers
onAppear view modifier only runs once, but you need to repeat the action after 1 min. take a look at this code may be helpful.
Here is a solution for you. In your question you said you were looking for an animation that scrolls left and right on repeat, so I assume you want to see it scroll across, then rewind and play again. This is a different kind of animation to a normal ticker, which usually just keeps looping in the same direction. However, if it is a ticker that you want then you can find solutions by searching SO, or you can adapt this one (it would be simpler).
This solution scrolls across, then rewinds at a faster speed and repeats the animation again. To do this it uses the technique I posted as an answer to Change Reverse Animation Speed SwiftUI. The width of the text is established by displaying it as the base view, then the animation is applied as an overlay over the top of it. The base view is masked out by applying a background to the overlay.
I added a delay to the start of the animation, although it doesn’t show in the animated gif. If you wanted a delay at the end too then this could be achieved by adapting the view modifier.