I’m developing a quiz app using the Swift language. After a user selects a button and then changes their mind to select a different button, the app considers the initially clicked button instead of the last one clicked. I’m storing the clicked values in a variable called ‘selectedValue’. The user moves to the next question by tapping the ‘next’ button.
@IBAction func buttonClicked(_ sender: UIButton) {
if sender.tag == 0 {
selectedValue += 0
} else if sender.tag == 1 {
selectedValue += 1
} else if sender.tag == 2 {
selectedValue += 2
} else if sender.tag == 3 {
selectedValue += 3
}
}
@IBAction func nextButtonClicked(_ sender: Any) {
nextQuestion()
}
How can I use the last clicked value instead of the initially clicked one?
>Solution :
So basing myself on your answer on my comment, I guess it’s a quiz where the user answer multiple questions, with no wrong answers and each answer contributing to an overall score, and the final score estimates the user depression.
The issue then is that, if the user chooses an answer and then changes his mind, you are incrementing selectedValue
multiple times for the same question.
Eg: fifth question, selectedValue
is equal to 10 before any answer to the question. User taps on the button with tag == 2
, then selectedValue == 12
. He changes his mind and selects the button with tag == 3
, then selectedValue
should be 13 but it’s 15 instead.
There are many ways to solve this, one of those is just to keep track of the previous selectedValue
before each question. You can declare another variable, in my example previousValue
, to track this. Then:
@IBAction func buttonClicked(_ sender: UIButton) {
// if the user taps multiple buttons for the same answer, you reset the previous taps this way
selectedValue = previousValue
if sender.tag == 0 {
selectedValue += 0
} else if sender.tag == 1 {
selectedValue += 1
} else if sender.tag == 2 {
selectedValue += 2
} else if sender.tag == 3 {
selectedValue += 3
}
}
@IBAction func nextButtonClicked(_ sender: Any) {
previousValue = selectedValue
nextQuestion()
}