0

i need a hint cause i don‘t know how to start. I want to display a string char after char with a short delay but I’m not sure how to do it. Should i convert the string into an array and display this array in a ForEach or is it possible to do this with string manipulation?

Thanks for every hint :-) Michael

1 Answer 1

1

Here's an example where you can input a String. It will turn it into an array of Strings (for each character), add them onto the screen using an HStack and Text objects. Each Text has initial .opacity of 0.0 and then a function is called that will loop through each Text, turning the .opacity to 1.0.

struct CharView: View {
    
    var characterArray: [String]
    @State var characterLoopIndex: Int = -1
    let loopDuration: Double = 0.5
    
    init(input: String) {
        characterArray = input.map { String($0) }
    }
    
    var body: some View {
        HStack(spacing: 0) {
            ForEach(characterArray.indices) { index in
                Text("\(characterArray[index])")
                    .opacity(characterLoopIndex >= index ? 1 : 0)
                    .animation(.linear(duration: loopDuration))
            }
        }
        .onAppear(perform: {
            startCharacterAnimation()
        })
    }
    
    func startCharacterAnimation() {
        let timer = Timer.scheduledTimer(withTimeInterval: loopDuration, repeats: true) { (timer) in
            
            characterLoopIndex += 1
            if characterLoopIndex >= characterArray.count {
                timer.invalidate()
            }
            
        }
        timer.fire()
    }
}

Usage:

CharView(input: "This is a test string")
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much. This is exactly what I’ve tried. But i thinked to complicated, your solution looks so easy :-) You and this forum helps my so much on my way into swift,
Hi nicksarno, I've tried your code and it works perfect. But I have one more questions: what can I do if the textstreng is longer than one line? adding a linelimit doesn't work...
That will be much more complicated, you will probably need to first split the input into words and then further into characters. Or maybe you can use multiple CharView's above in a VStack as an easy alternative.
I‘m trying this already. Seems not so easy. But with your code i have a good starting position!
I give it up. Seems not possible to me to implement a typewriter effect with a textview > 1 line...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.