skip to Main Content

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


  1. 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.

    struct ContentView: View {
        @Namespace var topID
        @Namespace var bottomID
        @State var atTop: Bool = false
    
        var body: some View {
            let baseAnimation = Animation.easeInOut(duration: 5)
    
            ScrollViewReader { proxy in
                ScrollView {
                    Text("")
                    .id(topID)
    
                    VStack(spacing: 0) {
                        ForEach(0..<100) { i in
                            color(fraction: Double(i) / 100)
                                .frame(height: 32)
                        }
                    }
                    
                    Text("")
                    .id(bottomID)
                }
                .onAppear{
                    atTop = true
                }
                .onChange(of: atTop) { newValue in
                    if newValue{
                        withAnimation(baseAnimation) {
                            proxy.scrollTo(bottomID)
                            DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
                                atTop = false
                            }
                        }
                    }else{
                        withAnimation(baseAnimation) {
                            proxy.scrollTo(topID)
                            DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
                                atTop = true
                            }
                        }
                    }
                }
            }
        }
        
    
        func color(fraction: Double) -> Color {
            Color(red: fraction, green: 1 - fraction, blue: 0.5)
        }
    }
    
    Login or Signup to reply.
  2. 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.

    struct OffsetModifier: ViewModifier, Animatable {
    
        private let maxOffset: CGFloat
        private let rewindSpeedFactor: Int
        private var progress: CGFloat
    
        // The progress value at which rewind begins
        private let rewindThreshold: CGFloat
    
        init(
            maxOffset: CGFloat,
            rewindSpeedFactor: Int = 4,
            progress: CGFloat
        ) {
            self.maxOffset = maxOffset
            self.rewindSpeedFactor = rewindSpeedFactor
            self.progress = progress
    
            // Compute the threshold at which rewind begins
            self.rewindThreshold = CGFloat(1) - (CGFloat(1) / CGFloat(rewindSpeedFactor + 1))
        }
    
        /// Implementation of protocol property
        var animatableData: CGFloat {
            get { progress }
            set { progress = newValue }
        }
    
        var xOffset: CGFloat {
            let fraction: CGFloat
            if progress > rewindThreshold {
                fraction = rewindThreshold - ((progress - rewindThreshold) * CGFloat(rewindSpeedFactor))
            } else {
                fraction = progress
            }
            return (fraction / rewindThreshold) * maxOffset
        }
    
        func body(content: Content) -> some View {
            content.offset(x: xOffset)
        }
    }
    
    struct RewindingTextTicker: View {
    
        let textKey: String
        let viewWidth: CGFloat
    
        let pixelsPerSec = 100
        @State private var progress = CGFloat.zero
    
        private func duration(width: CGFloat) -> TimeInterval {
            TimeInterval(max(width, 0)) / TimeInterval(pixelsPerSec)
        }
    
        var body: some View {
    
            // Display the full text on one line.
            // This establishes the width that is needed
            Text(LocalizedStringKey(textKey))
                .lineLimit(1)
                .fixedSize(horizontal: true, vertical: true)
    
                // Perform the animation in an overlay
                .overlay(
                    GeometryReader { proxy in
                        Text(LocalizedStringKey(textKey))
                            .modifier(
                                OffsetModifier(
                                    maxOffset: viewWidth - proxy.size.width,
                                    progress: progress
                                )
                            )
                            .animation(
                                .linear(duration: duration(width: proxy.size.width - viewWidth))
                                .delay(1.0)
                                .repeatForever(autoreverses: false),
                                value: progress
                            )
                            // Mask out the base view
                            .background(Color(UIColor.systemBackground))
                    }
                )
                .onAppear { progress = 1.0 }
        }
    }
    
    struct ContentView: View {
    
        private let fullText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
    
        var body: some View {
            VStack {
                GeometryReader { proxy in
                    RewindingTextTicker(
                        textKey: fullText,
                        viewWidth: proxy.size.width
                    )
                }
                .frame(height: 50)
            }
            .padding(.horizontal, 50)
        }
    }
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search