gpt4 book ai didi

ios - 如何在 Swift 中通过按下按钮来增加标签值

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:40 24 4
gpt4 key购买 nike

我试图在单击按钮时将标签递增 2。

import UIKit

class ViewController: UIViewController {

var cur = 0;

@IBOutlet weak var money: UILabel!

@IBAction func pressbutton(sender: UIButton) {
cur = money.text!.toInt()!;
self.money.text = String(cur + 2);

}

}

这是我当前的代码,但我收到了错误

toInt() is unavaliable: Use Int() initializer

在这条线上

cur = money.text!.toInt()!;

最佳答案

根据 MVC 编程,您不应该使用标签的内容来递增标签。相反,使用变量来存储您的 Int 并通过向变量添加属性观察器来更新标签,如下所示:

class ViewController: UIViewController {

@IBOutlet weak var someLabel: UILabel!

var someValue: Int = 0 {
didSet {
someLabel.text = "\(someValue)"
}
}

override func viewDidLoad() {
super.viewDidLoad()

someValue = 0 // didSet is called when the variable is changed, not upon initialization.
}

@IBAction func buttonPressed(sender: UIButton) {
someValue += 2
}
}

此外,我会考虑将您的变量重命名为比 cur 更具描述性的名称,并且您可以省略不必要的分号。

关于ios - 如何在 Swift 中通过按下按钮来增加标签值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734615/

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