swiftui - 按下按钮后如何创建指令提示?
问题描述
我正在创建一个说明对话框,该对话框将在按下按钮后启动。我希望指令显示在同一个视图中,并在几秒钟后被替换以显示下一条指令。
指令存储在文本数组中。
任何帮助将不胜感激,因为我无法找到解决方案
@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
}
}
}
解决方案
您可以为该值添加另一个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()
}
}
}
}
推荐阅读
- csv - 从 S3 将 .csv 格式的指标读入 prometheus
- c# - 非空对象上的 NullReference 异常
- laravel - Laravel:控制器资源索引不返回视图或字符串
- docker - Gitlab Runner Docker 容器无法连接到 Prometheus
- r - 如何在R中对条形图进行排序
- excel - 将一整列乘以 x 数
- python - 带有 IndexError 的 sns 绘图警告
- c# - 参数化动作调用委托
- python-2.7 - 为什么我在 ROS 中遇到“ModuleNotFoundError: No module named 'yaml'”?
- graphql - 使用 GraphQL Apollo 忽略该字段