我是Swift和Coding的新手。我的英语不太好,所以请提前道歉! 我想构建一个测验应用程序。现在,我无法检查正确的答案,因为可以选择我的uibutton。我想要拥有多个选择,多个正确答案的答案的原因。
我不知道您需要我的《代码》中的哪种信息,但我会发布我想提供的信息。
非常感谢您的帮助!
班级
import Foundation
class Quiz {
let question: String
let options : [String]
let correctAnswer: [String]
init(question: String, options: [String], correctAnswer: [String]) {
self.question = question
self.options = options
self.correctAnswer = correctAnswer
}
func validateOption(_ index: Int) -> Bool {
let answer = options[index]
return answer == correctAnswer[index]
}
deinit {
}
}
我的Viewcontroller
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var quenstionLabel: UILabel!
@IBOutlet var answerButton: [UIButton]!
let quizManager = QuizManager()
override func viewDidLoad() {
super.viewDidLoad()
getNewQuiz()
}
@IBAction func checkAnswerButtonTapped(_ sender: UIButton) {
}
@IBAction func checkMarkAnswerClicked(_ sender: UIButton) {
if sender.isSelected {
sender.isSelected = false
} else {
sender.isSelected = true
}
}
和我的测验经理
import Foundation
class QuizManager {
private var quiz: Quiz!
private var _totalAnswers = 0
private var _totalCorrectAnswers = 0
var question: String {
return quiz.question
}
var options: [String] {
return quiz.options
}
var totalAnswers: Int {
return _totalAnswers
}
var totalCorrectAnswers: Int {
return _totalCorrectAnswers
}
func refreshQuiz(){
let randomIndex = Int(arc4random_uniform(UInt32(quizes.count)))
let quizData = quizes[randomIndex]
quiz = Quiz(question: quizData.question, options: quizData.options, correctAnswer: quizData.correctAnswer)
}
func validateAnswer(index: Int){
_totalAnswers += 1
if quiz.validateOption(index){
_totalCorrectAnswers += 1
}
}
如果需要更多信息,请告诉我!!
如果有人可以帮助我,那就太好了。
答案 0 :(得分:1)
您可以按照以下步骤解决此问题。
//步骤1 var myAnswers:[String]
protocol CheckAnswerDelegate : class {
func didPressOptionButton(myAnswer: String)
}
@IBAction func buttonPressed(_ sender: UIButton) {
checkAnswerDelegate?.didPressOptionButton(myAnswer: self.answerButton.titleLabel?.text ?? "")
}
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, CheckAnswerDelegate {}
func didPressOptionButton(myAnswer: String) {
if question1.myAnswers.contains(myAnswer) {
if let firstIndex = question1.myAnswers.firstIndex(where: {$0 == myAnswer}) {
question1.myAnswers.remove(at: firstIndex)
}
}else {
question1.myAnswers.append(myAnswer)
}
self.answerView.reloadData()
}
答案 1 :(得分:0)
我要做的是将所有答案按钮都放在一个列表中。然后,在checkAnswerButtonTapped
内部,您可以浏览列表,查看其中哪些isSelected
设置为true。
for button in buttonList {
var answersSelected = []
if button.isSelected {
answersSelected.append(button.text)
// You may want something different here depending on how the buttons store the answer options
}
}
完成后,将它们与QuizManager
中预定义的正确答案进行比较。
可以使生活变得更轻松的另一件事是将.toggle()
函数与布尔变量一起使用。基本上,它只是切换变量的值。因此,在您的checkMarkAnswerClicked
中,您只需拥有sender.isSelected.toggle()