如何通过按下位于单独视图中的按钮来增加标签?
问题描述:
所以基本上我很熟悉应用程序开发和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
}
}
答
我相信它不工作的原因是因为你被分配修正值viewDidLoad方法标记之前分配0值。您可以实现这样的要求的行为:
修改结果视图控制器如下:
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
}
}