dankell
dankell

Reputation: 81

SwiftUI - How to make text appear using the button and then using the timer

I would like text from the dictinary to appear when the button is pressed. "Text1" is there at the beginning. If the button is pressed, a label with Text2 should appear under the start label. Then automatically a label with Text3 after 3 seconds. Originally I tried a list, but unfortunately I didn't get it. It would be great if someone has an idea.

struct ContentView: View {

   var chats = [
                "Text1" : "Hello?",
                "Text2" : "Here!",
                "Text3" : "And here!",
               ]

    var body: some View {

        NavigationView {

            VStack {
                Button(action: {}) {
                    Text("Button")
                }

                HStack {
                    Image (systemName: "faceid")
                    Text("\(chats["Text1"] ?? "Failure")")
                }
            }
        }
    }
}

Upvotes: 2

Views: 472

Answers (1)

shraddha11
shraddha11

Reputation: 773

Here is your solution. Please try this.

struct ContentView: View {

    var chats: [String: String] =  [
        "Text1" : "Hello?",
        "Text2" : "Here!",
        "Text3" : "And here!",
    ]

    @State var currentIndex: Int = 1


    var body: some View {

        NavigationView {
            VStack {
                Button(action: {
                    self.currentIndex = self.currentIndex + 1
                    if self.currentIndex == 2 {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                            self.currentIndex = self.currentIndex + 1
                        }
                    }
                 print("Hello, World! Tapped")
                }) {
                    Text("Hello, World!")
                }
                HStack {
                    Image (systemName: "faceid")
                    Text("\(chats["Text\(currentIndex)"] ?? "Failure")")
                }
            }
        }
    }
}

Upvotes: 2

Related Questions