Swift问答应用如何基于自定义结构体配置两个答题按钮
解决方案
你现有代码存在两个核心问题:
- 结构体设计冗余,
Answers结构体外层多套了一层无意义的数组,导致取值路径复杂容易出错 configure方法内取值逻辑错误,直接把数组类型赋值给按钮标题,且answer变量未定义
方案1:优化结构体设计(更推荐)
直接简化结构体结构,删除冗余嵌套,代码更易维护:
// 优化后的结构体,删除多余的Answers结构体 struct EasyQuestions { var question: String // 直接用字符串数组存两个选项 var answers: [String] var hint: String var correctAnswer: String } class QuizViewController: UIViewController { // 初始化题目数组,结构更简洁 var questions:[EasyQuestions] = [ EasyQuestions(question: "1 + 1", answers: ["5", "2"], hint: "3-1", correctAnswer: "2"), EasyQuestions(question: "2 + 2", answers: ["1", "4"], hint: "5-1", correctAnswer: "4") ] @IBOutlet weak var Question: UILabel! @IBOutlet weak var button1: UIButton! @IBOutlet weak var button2: UIButton! // 记录当前展示的题目索引 var currentQuestionIndex = 0 override func viewDidLoad() { super.viewDidLoad() configure(with: questions[currentQuestionIndex]) // 给按钮绑定点击事件 button1.addTarget(self, action: #selector(answerButtonTapped(_:)), for: .touchUpInside) button2.addTarget(self, action: #selector(answerButtonTapped(_:)), for: .touchUpInside) } func configure(with question: EasyQuestions){ self.Question.text = question.question // 正确给两个按钮设置标题 self.button1.setTitle(question.answers[0], for: .normal) self.button2.setTitle(question.answers[1], for: .normal) } // 按钮点击判断逻辑 @objc func answerButtonTapped(_ sender: UIButton) { let currentQuestion = questions[currentQuestionIndex] let selectedAnswer = sender.title(for: .normal) if selectedAnswer == currentQuestion.correctAnswer { print("回答正确") // 可自行添加答对后的提示、跳转下一题逻辑 } else { print("回答错误,提示:\(currentQuestion.hint)") // 可自行添加答错后的提示逻辑 } } }
方案2:保留原有结构体仅修改配置逻辑
如果你不想改动原有结构体定义,只需要修正configure方法的取值路径即可:
func configure(with question: EasyQuestions){ self.Question.text = question.question // 原有answers是数组,需要先取第一个元素再拿对应的answer字段 self.button1.setTitle(question.answers[0].answer1, for: .normal) self.button2.setTitle(question.answers[0].answer2, for: .normal) }
内容的提问来源于stack exchange,提问作者Bon Doe
相关产品推荐
相关产品推荐

