将整数更新为 swift 中的标签

Updating a integer as a label in swift

我想通过按下按钮来更改标签的数值。我曾经收到错误说你不能把数字放在字符串中,所以,我做了字符串(变量)。它现在显示基本数字 1,但是当我点击它时,它没有更新!

以下是我设置变量的方式: 首先,我将按钮设置为 IBAction。这是其中的代码:

@IBOutlet weak var NumberOfExploits: UILabel!
@IBAction func exploiter(sender: AnyObject) {
    var hacks = 0
    hacks += 1
    NumberOfExploits.text = String(hacks)   
}

谁能帮忙看看怎么改号?

第一个:

let用于常量,不可更改。 var 用于变量。

第二个:

加一是用 += 1= myVariable + 1

var myVariable = 1

myVariable += 1
label.text = string(myVariable)

重要的是要了解您的变量仅在封闭的 class 或函数存在时存在。因此,当您在函数内声明变量、常量时(使用 var let 是声明),当函数完成时它就会消失。 UIViewcontroller 会一直存在,只要你愿意。所以在那里声明你以后需要的东西。

import UIKit

// things that live here are at the "global level"


// this is a viewcontroller. It is a page in your app.
class ViewController: UIViewController {

    // things that live here are at the "class level"

    var myClassCounter : Int = 0

    // button in interfacebuilder that is connected through an outlet.
    @IBOutlet weak var myButton: UIButton!


    override func viewDidLoad() {
        super.viewDidLoad()

        // this is a function that gets called when the view is loaded
    }

    override func viewDidAppear(animated: Bool) {
        // this is a function that gets called when the view appeared

    }


    // button function from interface builder
    @IBAction func myButtonIsTouched(sender: AnyObject) {
        // this will be destroyed when the function is done
        var myFunctionCounter = 0
        myFunctionCounter += 1

        // this will be stored at class level
        myClassCounter += 1
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

你也可以这样做

label.text = "\(variable)"

这会将数字显示为字符串。

最重要的是在 class 内但在任何函数外声明变量

var variable = 1

那就这样写IBAction函数

@IBAction func pressButton(sender : UIButton)
{
  label.text = "\(++variable)"
}

语法 ++variable 将变量递增 1。
语法 "\(v)" 创建可表示为字符串的任何字符串