is there any way to show an array of texts sequentially in swiftui?

Here is a possible solution:

struct TimedTextContainer: View {
    @State private var currentIndex = 0
    @State private var isVisible = true

    let textArray: [String]

    var visibilityFor: TimeInterval
    var delay: TimeInterval

    var body: some View {
        if currentIndex < textArray.count, isVisible {
            Text(textArray[currentIndex])
                .font(.largeTitle)
                .id(currentIndex)
                .transition(.asymmetric(insertion: .opacity, removal: .opacity))
                .animation(.easeIn)
                .onAppear {
                    DispatchQueue.main.asyncAfter(deadline: .now() + visibilityFor) {
                        withAnimation {
                            isVisible = false
                        }
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + visibilityFor + delay) {
                        withAnimation {
                            currentIndex += 1
                            isVisible = true
                        }
                    }
                }
        }
    }
}
struct ContentView: View {
    let textArray = ["Hey there!", "What's your name?"]

    var body: some View {
        TimedTextContainer(textArray: textArray, visibilityFor: 3, delay: 1)
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top