首先,对不起我的英语不好!我绝对是SwiftUI的新手,我尝试创建一个具有多个选择和多个答案的测验应用程序。我创建了一个带有ForEach的按钮,以显示可能的答案。现在,我想选择正确的答案,然后点击复选按钮以验证所选答案。可以有1个以上的正确答案。
我尝试了此函数,但只有一个或两个,它只会返回
//MARK:- Funktionen
func checkAnswer() {
if validateAnswer == quiz.correctAnswer {
print("Richtig")
} else {
print("Falsch")
}
}
我不知道如何用正确的答案来验证所选答案。谁能帮我? 这是我的代码: QuizModel
struct Quiz: Identifiable {
var id: String = UUID().uuidString
var question: String
var howManyAnswers: String
var options: [PossibleAnswer]
var correctAnswer: [String]
var explain: String
}
extension Quiz: Equatable {}
struct PossibleAnswer : Identifiable, Equatable {
let id = UUID()
let text : String
}
ContentView
struct ContentView: View {
var quiz: Quiz
@State var isChecked:Bool = false
@State private var showAlert: Bool = false
@State var validateAnswer: [String] = ["Antwort 3", "Antwort 4"]
//MARK:- Answers
VStack {
ForEach(quiz.options) { answerOption in
QuizButtonView(isChecked: isChecked, title: answerOption.text)
.foregroundColor(.black)
.padding(2.0)
}
Spacer()
Divider()
HStack {
//MARK:- Button Überprüfen & Zurück
Button(action: {
print("Ich gehe zurück")
}, label: {
Text("Zurück")
})
Button(action: {
checkAnswer()
print("Ich überprüfe...")
self.showAlert.toggle()
}, label: {
Text("Überprüfen")
})
.padding(.leading, 200)
还有我的CheckButtonView
struct QuizButtonView: View {
@State var isChecked:Bool = false
var title:String
func toggle(){
isChecked.toggle()
if self.isChecked == true {
print("Antwort wurde ausgewählt")
} else if self.isChecked == false {
print("Antwort wurde wieder abgewählt")
}
}
var body: some View {
VStack {
Button(action: toggle) {
HStack{
Text(title)
.font(.system(size: 16))
.foregroundColor(.black)
.lineLimit(3)
Spacer()
Image(systemName: isChecked ? "checkmark.square.fill": "square")
}
}
谢谢!
答案 0 :(得分:1)
您只需要创建一个布尔数组的状态变量:
struct ContentView: View {
private let quiz: Quiz
@State private var userSelections: [Bool]
init(quiz: Quiz) {
self.quiz = quiz
_userSelections = State(initialValue: Array(repeating: false, count: quiz.options.count))
}
var body: some View {
VStack {
ForEach(0..<quiz.options.count) { index in
QuizButtonView(isChecked: userSelections[index], title: quiz.options[index].text)
.foregroundColor(.black)
.padding(2.0)
}
}
}
func checkAnswer() {
let userSelectionTexts = Set(userSelections.enumerated().map({ quiz.options[$0.offset].text }))
let correctAnswers = Set(quiz.correctAnswer)
let isAllSelectionsTrue = userSelectionTexts == correctAnswers
let isAllSelectionsFalse = userSelectionTexts.intersection(correctAnswers).isEmpty
let isAnySelectionsTrue = !isAllSelectionsFalse
}
}