按钮操作以遍历数组中的项目

时间:2019-09-10 00:11:51

标签: arrays function swiftui

我正在尝试创建一个按钮动作,当按下按钮时,它将显示数组中的下一项。

这是数据模型:

struct Option: Identifiable {
let id = UUID()
let itemLabel: String
let choice1: String
let choice2: String
let choice3: String
let choice4: String
let correctItem: String

}

extension Option {
static func all() -> [Option] {
    return [
        Option(itemLabel: "Vulputate Justo Aenean Mattis Porta", choice1: "A", choice2: "B", choice3: "C", choice4: "D", correctItem: "D"),
        Option(itemLabel: "Vulputate Justo Aenean Mattis Porta", choice1: "A", choice2: "B", choice3: "C", choice4: "D", correctItem: "D")
]
}
}

所以我试图弄清楚如何创建遍历数组中各项的函数。按下按钮后,我希望能够在文本元素中显示以下“ itemLabel”文本,以替换先前的文本。

 Text(Option.all()[0].itemLabel)

以上是我当前显示itemLabel的方式

1 个答案:

答案 0 :(得分:0)

我认为这是您想要做的:

struct ContentView: View {
    @State private var idx = 0

    var body: some View {
        VStack {
            Text(Option.all()[idx].itemLabel)

            Button("Toggle direction") {
                self.idx = (self.idx + 1 < Option.all().count) ? self.idx + 1 : 0
            }
        }
    }
}


struct Option: Identifiable {
    let id = UUID()
    let itemLabel: String
    let choice1: String
    let choice2: String
    let choice3: String
    let choice4: String
    let correctItem: String

}

extension Option {
    static func all() -> [Option] {
        return [
            Option(itemLabel: "Text A", choice1: "A", choice2: "B", choice3: "C", choice4: "D", correctItem: "D"),
            Option(itemLabel: "Text B", choice1: "A", choice2: "B", choice3: "C", choice4: "D", correctItem: "D"),
            Option(itemLabel: "Text C", choice1: "A", choice2: "B", choice3: "C", choice4: "D", correctItem: "D")
        ]
    }
}