Как я могу проверить ответы текстового поля, используя swift? - PullRequest
0 голосов
/ 22 марта 2020

Я пишу базовое c приложение для викторин в XCode, используя одну страницу, и мне нужна помощь о том, как я могу проверить ответы. У меня есть ряд вопросов и ответов, которые совпадают. Когда пользователь вводит свой ответ в текстовое поле, как я могу проверить его правильность?

@IBOutlet var questionLabel:UILabel!
@IBOutlet var answerField:UITextField!
@IBOutlet var instructionsLabel:UILabel!


let questions:[String] = ["In what country is the Christ the Redeemer statue located in?", "In what country is Machu Picchu lacated in?", "In what country is the Taj Mahal located in?", "In what country is the Great Pyramids of Giza located in?","In what country is Petra located in?","In what country is the Great Wall located in?", "In what country is the ruins if Chichen Itza located in?"]
let answers:[String] = ["Brazil", "Peru", "India", "Egypt", "Jordan", "China", "Mexico"]


var currentQuestionIndex:Int = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    currentQuestionIndex = questions.count - 1
}
@IBAction func showNextQuestion(sender:AnyObject){

    if(currentQuestionIndex<questions.count-1) {
        currentQuestionIndex = currentQuestionIndex + 1
    } else {
        currentQuestionIndex = 0
    }
    questionLabel.text = questions[currentQuestionIndex]

}

@IBAction func checkAnswer(){

}

}

1 Ответ

0 голосов
/ 23 марта 2020

Вот один из способов проверить ответ

@IBAction func checkAnswer() {
    guard let answer = answerField.text, !answer.isEmpty else {
        //answer is empty
        return
    }

    if answers[currentQuestionIndex].lowercased() == answer.lowercased() {
        //correct answer found
    } else {
        //Incorrect answer
    }
}

Обратите внимание, что я не написал никакого кода для отображения результата пользователю, но вы могли бы, например, иметь метку, где вы пишете сообщение, где Я только что написал комментарий. Более сложным решением может быть отображение сообщения о результате в виде предупреждения или в виде листа.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...