简体   繁体   English

如何在Swift中按下按钮来增加标签值

[英]How do I increment a label value with a button press in Swift

I am trying to increment a label by 2 when I click a button. 当我点击一个按钮时,我试图将标签增加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);

    }

}

Here is my current code but I am getting the error 这是我当前的代码,但我收到错误

toInt() is unavaliable: Use Int() initializer toInt()是不可用的:使用Int()初始值设定项

on this line 在这条线上

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

You shouldn't be using the content of a label to increment your label according to MVC programming. 根据MVC编程,您不应该使用标签的内容来增加标签。 Instead, use a variable to store your Int and update the label by adding a property observer to the variable like so: 相反,使用变量来存储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
    }
}

Also, I would consider renaming your variable to something more descriptive than cur , and you may omit the semicolons as they are unnecessary. 此外,我会考虑将您的变量重命名为比cur更具描述性的内容,并且您可以省略分号,因为它们是不必要的。

You can fix this error by changing the offending code to the following: 您可以通过将违规代码更改为以下内容来修复此错误:

cur = Int(money.text!)!;

Read more about initializers here . 在此处阅读有关初始值设定项 An excerpt: 摘录:

Initialization is the process of preparing an instance of a class, structure, or enumeration for use. 初始化是准备要使用的类,结构或枚举的实例的过程。 This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use. 此过程涉及为该实例上的每个存储属性设置初始值,并执行在新实例准备好使用之前所需的任何其他设置或初始化。

money.text = "\(Int(money.text!)! + 2)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM