-1

I'm creating an instruction dialog that will start after pressing a button. I want the instruction to be displayed in the same view and just get replaced after a few seconds to display the next instruction.

The instructions are stored in a text array.

Any help will be greatly appreciated as I'm having trouble finding a solution

@State var showPrompt = false
@State var textToUpdate = ""
let instructionTo = ["hi", "bye"]

VStack {

    Text(textToUpdate)
        .frame(width: UIScreen.main.bounds.width - 80, height: 350)
    Button(action: {
            if(self.showPrompt == false)
            {
                self.showPrompt = true
            }
            else{
                self.showPrompt = false
            }
        }) {
            if(self.showPrompt == false)
            {
                 Text("Start")
            }
            else
            {
                 Text("Stop")
                 // some for loop that would update the text
                 // and have a delay of 5 seconds between each 
                 // index in the array
            }
        }

}
John B
  • 21
  • 2

1 Answers1

0

you can add another State variable for the Text value.

here is a sample code, assuming that you want to start changing the text after tapping on the start button after 5 seconds. I just added an empty string to show an empty text at first.

struct TestView: View {
    @State var showPrompt = false
    @State var textIndex = 0
    let instructionTo = ["", "hi", "bye"]
    
    var body: some View {
        
        VStack {

            Text(instructionTo[textIndex])
                .frame(width: UIScreen.main.bounds.width - 80, height: 350)
            Button(action: {
                    if(self.showPrompt == false)
                    {
                        self.showPrompt = true
                        // update text value
                        self.updateText()
                    }
                    else{
                        self.showPrompt = false
                    }
                }) {
                    if(self.showPrompt == false)
                    {
                         Text("Start")
                    }
                    else
                    {
                         Text("Stop")
                    }
                }

        }
    }
    
    func updateText() {
        if self.textIndex < self.instructionTo.count - 1 {
            // update text after 5 seconds
            DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                self.textIndex += 1
                self.updateText()
            }
        }
    }

}
Mohammad Rahchamani
  • 5,002
  • 1
  • 26
  • 36