I've got a problem with leading zero in my simple app (Calculator). On start Zero is printed on label, but when I tap button for example "1" I see "01". It doesn't look good, so I would to change it. My code is below. Can somebody help me in it?
import UIKit
class ViewController: UIViewController {
var previousValue:Int?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typicala nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//display
@IBOutlet weak var displayLabel: UILabel!
// buttons
@IBAction func buttonPressed(sender: AnyObject) {
let numb = (sender as! UIButton).tag
displayLabel.text = "\(displayLabel.text!)\(numb)"
}
//plus
@IBAction func plusPress(sender: AnyObject) {
previousValue = Int(displayLabel.text!)
displayLabel.text = "+"
}
//minus
@IBAction func minusPress(sender: AnyObject) {
previousValue = Int(displayLabel.text!)
displayLabel.text = "-"
}
// count
@IBAction func count(sender: AnyObject) {
let result = previousValue! + Int(displayLabel.text!)!
displayLabel.text = "\(result)"
}
@IBAction func clear(sender: AnyObject) {
displayLabel.text=""
}
}
Check the contents of displayLabel.text
first. If it is 0
, then just set displayLabel.text
to the number that was pressed. Also, if you declare sender
in buttonPressed
to be a UIButton
, then you don't have to cast it:
@IBAction func buttonPressed(sender: UIButton) {
let numb = sender.tag
if displayLabel.text == "0" {
displayLabel.text = "\(numb)"
}
else {
displayLabel.text = "\(displayLabel.text!)\(numb)"
}
}