【问题标题】:How to create an instruction prompt after pressing a button?按下按钮后如何创建指令提示?
【发布时间】:2020-09-20 19:47:54
【问题描述】:

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

指令存储在文本数组中。

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

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

}

【问题讨论】:

  • 请发布您的一些代码和您想要实现的目标的图像。
  • 刚刚更新!立即查看
  • @JohnB 作为替代方案,您可以使用 PageTabViewStyle 查看 TabView - 请参阅 this answer。如果您想创建一个入职视图,它可能会对您有所帮助。

标签: swiftui


【解决方案1】:

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

这是一个示例代码,假设您想在 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()
            }
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2019-11-16
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    相关资源
    最近更新 更多