我想通过按下按钮来更改标签的数字值。我曾经得到错误,说你不能把数字放在一个字符串中,所以,我做了字符串(变量)。它现在显示基本数字1,但是当我点击它时,它不会更新!
以下是我设置变量的方法: 首先,我将按钮设置为IBAction。以下是其中的代码:
@IBOutlet weak var NumberOfExploits: UILabel!
@IBAction func exploiter(sender: AnyObject) {
var hacks = 0
hacks += 1
NumberOfExploits.text = String(hacks)
}
有人可以帮忙找出如何更改号码吗?
答案 0 :(得分:3)
首先:
let
用于常量,这些不能更改。
var
用于变量。
第二
使用+= 1
或= myVariable + 1
var myVariable = 1
myVariable += 1
label.text = string(myVariable)
重要的是要理解,只要封闭的类或函数处于活动状态,您的变量才会存在。因此,当您声明一个变量时,函数内部的常量(使用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.
}
}
答案 1 :(得分:1)
您也可以这样做
label.text = "\\(variable)"
将数字显示为字符串。
答案 2 :(得分:0)
最重要的是在类中声明变量但在任何函数之外
var variable = 1
然后以这种方式编写IBAction
函数
@IBAction func pressButton(sender : UIButton)
{
label.text = "\(++variable)"
}
语法++variable
将变量递增1
语法"\(v)"
创建一个字符串可以表示字符串