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

Can't increment variable in Swift - not throwing any errors

(我是编程新手,所以非常感谢外行友好的回答)

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

在我的模型文件中声明

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

在我的视图控制器中

    @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)"
    }

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

当您在 viewDidLoad 中创建 scoreLabel 时,您为其分配了一个很棒的文本值 "Score: \(teamOneScore)"。但是,当您增加 teamOneScore 变量时,实际的 UILabel 并不知道要更改其 text。它假定您想要显示 Score: 0。即使一个变量改变了它的值,该标签已经创建并将继续显示任何初始化的文本。

你需要在你的 buttonPressed 函数中做的是添加

scoreLabel.text = "Score: \(teamOneScore)"scoreLabel.text = "Score: \(teamOneScore)" 如果是第 2 队得分。

增加分数后。这就是允许标签文本实际更改的原因。

您必须使用额外的方法移动文本设置。现在文本仅在 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()
}