如何通过按下按钮来检查UIbutton是否正确

时间:2018-09-27 13:21:56

标签: swift uibutton

我在一个4选项问题中创建了4个UIbutton。此处的代码用于检查是否选择了正确的答案。为什么if语句每次都返回false?我知道这里有问题,但是我是新手,不能自己解决。请帮忙,非常感谢!

let question1 = Question(question: "This was the only US President to serve more than two consecutive terms.", options: ["George Washington", "Woodrow Wilson", "Andrew Jackson", "Franklin D. Roosevelt"], correctAnswer: "Franklin D. Roosevelt")

@IBAction func checkAnswer(_ sender: UIButton) {

    let correctAnswer = question1.correctAnswer

    if sender.currentTitle == correctAnswer {
        sender.backgroundColor = UIColor.black
    }
}

2 个答案:

答案 0 :(得分:0)

我认为这会对您有所帮助。

@IBAction func checkAnswer(_ sender: UIButton) {

    let correctAnswer = selectedQuestionDict["Answer"]

    if sender.titleLabel?.text == correctAnswer {
        sender.backgroundColor = UIColor.black
    }
}

答案 1 :(得分:0)

设置selected(或更常见的是normal状态)的按钮标题:

let btn = UIButton()
btn.setTitle("Franklin D. Roosevelt", for: .normal)
//Or
btn.setTitle("Franklin D. Roosevelt", for: .selected)

有关currentTitle的更多详细信息,请查看here