我正在创建一个测验应用程序,其中每个测验问题都是一个分组的TableView,每个单元格都是一个答案选项,并嵌入到导航控制器中。对于用户点击的每一个正确答案,我希望他们的得分增加1。我在我的导航控制器中设置了一个得分标签作为rightBarButtonItem。
下面是我在viewDidLoad( )中创建栏按钮项的方法:
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Score: \(score)", style: .plain, target: nil, action: Selector(("updateScore")))我有一个包含数组questionsList的模型类Question,该数组包含以下属性: questionString、answers[]、selectedAnswerIndex (nil)和correctAnswerIndex (int)
updateScore方法:
@objc func updateScore() {
for question in questionsList {
if question.selectedAnswerIndex == question.correctAnswerIndex {
score += 1
}
}
}有什么想法吗?我尝试了另一种方法,将分数标签放在页脚视图中,使用viewForFooterInSection作为表控制器,并将for循环放入我的didSelectRowAt方法中,但分数标签也不会在那里更新。
发布于 2019-08-16 08:30:20
在更新score之后,您需要创建并分配一个新的栏按钮项。您不能更新现有按钮的文本。
在您的for循环之后,添加:
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Score: \(score)", style: .plain, target: nil, action: Selector(("updateScore")))是的,它与创建原始按钮时所显示的代码相同。
更好的方法是更新您的score属性:
var score: Int = 0 {
didSet {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Score: \(score)", style: .plain, target: nil, action: Selector(("updateScore")))
}
}然后更新你的updateScore
@objc func updateScore() {
var newScore = score
for question in questionsList {
if question.selectedAnswerIndex == question.correctAnswerIndex {
newScore += 1
}
}
score = newScore
}然后更新viewDidLoad (或其他任何地方),删除当前创建栏按钮项的调用,然后简单地执行以下操作:
score = 0 // or some other appropriate initial valuehttps://stackoverflow.com/questions/57517635
复制相似问题