首页 > 解决方案 > 如何使用 swift 检查文本字段的答案?

问题描述

我正在使用单个页面在 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(){

}

}

标签: swiftstringxcode

解决方案


这是检查答案的一种方法

@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
    }
}

请注意,我没有编写任何代码来向用户显示结果,但是您可以有一个标签,您可以在其中写一条消息,而我刚刚写了一条评论。更高级的解决方案可能是将结果消息显示为警报或工作表。


推荐阅读