英文:
Updating Last Clicked Button
问题
如何使用最后点击的值而不是最初点击的值?
英文:
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?
答案1
得分: 0
根据您在我的评论中的回答,我猜这是一个测验,用户回答多个问题,没有错误答案,每个答案都有助于总体分数,最终分数估计用户的抑郁症。
问题在于,如果用户选择了一个答案,然后改变主意,您会为同一个问题多次递增selectedValue
。
例如:第五个问题,在回答问题之前,selectedValue
等于10。用户点击tag == 2
的按钮,然后selectedValue == 12
。他改变主意,选择tag == 3
的按钮,然后selectedValue
应该是13,但实际上是15。
有许多解决方法,其中之一是在每个问题之前跟踪先前的selectedValue
。您可以声明另一个变量,在我的示例中是previousValue
,来跟踪这个值。然后:
@IBAction func buttonClicked(_ sender: UIButton) {
// 如果用户为同一个答案点击多次按钮,您可以通过以下方式重置先前的点击
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()
}
请注意,这是您提供的代码的一部分,不包括任何其他内容。
英文:
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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论