swift - 如何通过按下 UIbutton 来检查它是否是正确答案

标签 swift uibutton

我在一个 4 选项问题中创建了 4 个 UI 按钮。这里的代码是检查是否选择了正确的答案。为什么 if 语句每次都返回 false?我知道这里出了问题,但我对 swift 很陌生,无法自己修复它。请帮忙,非常感谢!

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

最佳答案

设置选定(或更一般的正常状态)的按钮标题:

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

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

关于swift - 如何通过按下 UIbutton 来检查它是否是正确答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52538036/

相关文章:

ios - 如何将图像加载到 iOS 应用程序中

ios - SpriteKit 黑屏

iphone - UIButton.layer.cornerRadius 不存在?

ios - 未调用 UIButton 目标操作

ios - 将 UIViewcontroller 加载到比屏幕小的 s​​crollView 中?

swift - 如何在 Swift 3 的子类之间共享变量?

iOS Swift - 如何以编程方式为所有按钮分配默认操作

ios - 更改突出显示的 UIButton BG 颜色,但保留层角半径?

ios - 使用动画快速更改圆形边框颜色

swift - 如何使用 Set.intersection 获取两个序列的元素列表