首页 > 解决方案 > 按下按钮后如何创建指令提示?

问题描述

我正在创建一个说明对话框,该对话框将在按下按钮后启动。我希望指令显示在同一个视图中,并在几秒钟后被替换以显示下一条指令。

指令存储在文本数组中。

任何帮助将不胜感激,因为我无法找到解决方案

@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
            }
        }

}

标签: swiftui

解决方案


您可以为该值添加另一个State变量Text

这是一个示例代码,假设您想在 5 秒后点击开始按钮后开始更改文本。我刚开始添加了一个空字符串来显示一个空文本。

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()
            }
        }
    }

}

推荐阅读