I am creating a quiz app where each question in the quiz is presented by a tableview embedded in a navigationcontroller. I have a score label set in the right bar button item of the navigation controller that I want to update each time a user chooses an answer (tableviewcells). I can't seem to get the score label to update with my code.. Any thoughts?
Btw there is more stuff in my viewDidLoad but i just kept the relevant stuff in for the code snippet.
var score: Int = 0 {
didSet {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Score: \(score)", style: .plain, target: nil,
action: Selector(("updateScore")))
}
}
override func viewDidLoad() {
super.viewDidLoad()
score = 0
}
@objc func updateScore() {
var newScore = score
for question in questionsList {
if question.selectedAnswerIndex == question.correctAnswerIndex {
newScore += 1
}
}
score = newScore
}
Also the selectedAnswerIndex and correctAnswerIndex comes from my question model class that contains the quiz questions in my questionsList array. Is this possible to do with a bar button item or should I be looking into other ways to represent the score..?