如何将ViewController扩展数据传递给按钮点击函数并实现选项变色
解决方案
要实现点击选项后正确答案变绿、错误选项变红的功能,核心是在ViewController中保留当前题目的数据,让按钮点击事件能访问到正确答案。以下是具体修改步骤:
1. 在ViewController中添加当前题目存储属性
在ViewController类里添加可选类型的QuizModel属性,用于保存当前加载的题目数据,让按钮点击函数能直接访问正确答案:
class ViewController: UIViewController { // ... 现有IBOutlet和属性 ... var currentQuiz: QuizModel? // 新增:存储当前题目 // ... 其余代码 ... }
2. 优化选项处理并保存当前题目
在didUpdateQuiz代理方法中,简化选项数组的构建逻辑,同时将获取到的quiz赋值给currentQuiz,并重置按钮状态:
extension ViewController : quizManagerDelegate{ func didUpdateQuiz(_ Quizmanager: QuizManager, quiz: QuizModel) { DispatchQueue.main.async { [self] in self.currentQuiz = quiz // 保存当前题目 self.QuestionTextView.text = quiz.question // 构建所有选项数组并打乱顺序 var allOptions: [String] = quiz.falseAnswer allOptions.append(quiz.correctAnswer) let shuffledOptions = allOptions.shuffled() // 重置按钮状态:恢复默认背景色、启用按钮 let buttons = [ChoiceButton1, ChoiceButton2, ChoiceButton3, ChoiceButton4] buttons.forEach { $0?.backgroundColor = .systemBlue // 替换成你需要的默认按钮颜色 $0?.isEnabled = true } // 给按钮设置标题 ChoiceButton1.setTitle(shuffledOptions[0], for: .normal) ChoiceButton2.setTitle(shuffledOptions[1], for: .normal) ChoiceButton3.setTitle(shuffledOptions[2], for: .normal) ChoiceButton4.setTitle(shuffledOptions[3], for: .normal) } } }
3. 实现按钮点击的颜色逻辑
在OptionsButtonPressed函数中,通过currentQuiz获取正确答案,对比用户选中的选项,设置对应颜色并禁用按钮防止重复点击:
@IBAction func OptionsButtonPressed(_ sender: UIButton) { // 禁用所有按钮,避免重复操作 [ChoiceButton1, ChoiceButton2, ChoiceButton3, ChoiceButton4].forEach { $0?.isEnabled = false } // 安全获取选中的答案和当前题目数据 guard let selectedAnswer = sender.title(for: .normal), let currentQuiz = currentQuiz else { return } if selectedAnswer == currentQuiz.correctAnswer { // 选中正确答案:设置按钮为绿色 sender.backgroundColor = .green } else { // 选中错误答案:设置当前按钮为红色,同时找到正确答案的按钮设为绿色 sender.backgroundColor = .red let buttons = [ChoiceButton1, ChoiceButton2, ChoiceButton3, ChoiceButton4] buttons.forEach { button in if button?.title(for: .normal) == currentQuiz.correctAnswer { button?.backgroundColor = .green } } } }
额外优化点
- 简化了选项数组的构建方式,直接基于
quiz.falseAnswer追加正确答案,避免重复的append调用。 - 每次加载新题目时重置按钮状态,确保用户体验一致。
内容的提问来源于stack exchange,提问作者Mert
相关产品推荐
相关产品推荐

