I am trying to increment a label by 2 when I click a button.
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
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. Instead, use a variable to store your Int
and update the label by adding a property observer to the variable like so:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With