gpt4 book ai didi

swift - 无法在 Swift 中增加变量 - 不抛出任何错误

转载 作者:可可西里 更新时间:2023-11-01 01:40:02 25 4
gpt4 key购买 nike

(我对编程很陌生,所以非常感谢外行友好的回答)

我正在开发一款由两支球队进行的游戏。我有一个按钮可以检查哪支球队上场,然后更新该球队的得分。代码运行没有错误,但按下按钮时分数不会更新。

在我的模型文件中声明

var teamOneScore = 0
var teamTwoScore = 0
var teamCounter = 2

在我的 View Controller 中

    @IBAction func buttonPressed(sender: AnyObject) {
if timer.valid && teamCounter % 2 == 0 {
++teamOneScore
} else if timer.valid && teamCounter % 2 != 0 {
++teamTwoScore
}
}

在viewDidLoad中

        if teamCounter % 2 == 0 {
scoreLabel.text = "Score: \(teamOneScore)"
} else {
scoreLabel.text = "Score: \(teamTwoScore)"
}

加载 View 时,scoreLabel 正确显示 0,但是当我按下按钮时,显示的分数没有上升。计时器和 teamCounter 检查在代码的其他任何地方都工作正常,我有另一个按钮可以毫无问题地递增 teamCounter(它也作为 int 存储在模型中)。所以 buttonPressed 的所有单独组件似乎都工作正常,我没有任何错误可以继续。我很难过。

最佳答案

您必须使用额外的方法移动文本设置。现在,文本仅在 viewDidLoad 中设置 - 但是该函数不会被触发不止一次。

将您的 viewDidLoad 更改为类似的内容

updateUI()

添加一个新函数

func updateUI() {
if teamCounter % 2 == 0 {
scoreLabel.text = "Score: \(teamOneScore)"
} else {
scoreLabel.text = "Score: \(teamTwoScore)"
}
}

并将该方法作为按钮操作中的最后一件事调用:

@IBAction func buttonPressed(sender: AnyObject) {
if timer.valid && teamCounter % 2 == 0 {
++teamOneScore
} else if timer.valid && teamCounter % 2 != 0 {
++teamTwoScore
}
updateUI()
}

关于swift - 无法在 Swift 中增加变量 - 不抛出任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30697360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com