Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

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()!;
like image 242
StackOverflower Avatar asked Jun 09 '15 14:06

StackOverflower


1 Answers

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.

like image 147
Ian Avatar answered Nov 09 '22 22:11

Ian