基本上我对应用程序开发和Xcode很熟悉,但我还处于学习的开始阶段,我需要一些帮助。我创建了一个情绪测验类型的用户界面,在10个问题的最后,我有一个页面,显示用户在整个测验中获得的不同情绪和分数。我需要帮助的是用户单击问题1上的按钮以使我的结果页面上的标签增加1.我到目前为止尝试了许多不同的方法,但似乎无法弄明白。我已将我的按钮链接到各自的视图控制器作为操作,并将标签链接到各自的视图控制器作为插座。
import UIKit
class Question1: UIViewController {
@IBAction func buttonlightgreen(_ sender: UIButton) {
print ("light green")
sadscoreText += 1
}
@IBAction func buttonred(_ sender: Any) {
print ("red")
angryscoreText += 2
happyscoreText += 1
}
@IBAction func buttonpurple(_ sender: Any) {
print ("purple")
annoyedscoreText += 1
stressedscoreText += 1
}
@IBAction func buttondarkgreen(_ sender: Any) {
print ("dark green")
relaxedscoreText += 2
tiredscoreText += 1
}
@IBAction func buttonyellow(_ sender: Any) {
print ("yellow")
happyscoreText += 1
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
这是按钮的代码,这是标签的代码。
import UIKit
var sadscoreText = 0
var happyscoreText = 0
var relaxedscoreText = 0
var angryscoreText = 0
var annoyedscoreText = 0
var tiredscoreText = 0
var stressedscoreText = 0
class Results: UIViewController {
@IBOutlet weak var sadscore: UILabel!
@IBOutlet weak var happyscore: UILabel!
@IBOutlet weak var relaxedscore: UILabel!
@IBOutlet weak var angryscore: UILabel!
@IBOutlet weak var annoyedscore: UILabel!
@IBOutlet weak var tiredscore: UILabel!
@IBOutlet weak var stressedscore: UILabel!
var sadscoreText: Int = 0 {
didSet {
sadscore.text = "\(sadscoreText)"
}
}
override func viewDidLoad() {
super.viewDidLoad()
sadscoreText = 0
happyscoreText = 0
relaxedscoreText = 0
angryscoreText = 0
annoyedscoreText = 0
tiredscoreText = 0
stressedscoreText = 0
}
}
答案 0 :(得分:1)
我认为它不起作用的原因是因为在将修改后的值分配给viewDidLoad方法中的标签之前,您要为值赋值0。您可以像这样实现所需的行为:
修改Results视图控制器,如下所示:
import UIKit
var sadscoreText = 0
var happyscoreText = 0
var relaxedscoreText = 0
var angryscoreText = 0
var annoyedscoreText = 0
var tiredscoreText = 0
var stressedscoreText = 0
class Results: UIViewController {
@IBOutlet weak var sadscore: UILabel!
@IBOutlet weak var happyscore: UILabel!
@IBOutlet weak var relaxedscore: UILabel!
@IBOutlet weak var angryscore: UILabel!
@IBOutlet weak var annoyedscore: UILabel!
@IBOutlet weak var tiredscore: UILabel!
@IBOutlet weak var stressedscore: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
sadscore.text = "\(sadscoreText)"
happyscore.text = "\(happyscoreText)"
//follow the same for other labels
//you can set the values again to zero after showing the labels on the screen like this
sadscoreText = 0
happyscoreText = 0
}
}