计算器swift2中的前导零

时间:2015-10-23 06:54:18

标签: ios swift2 leading-zero

我的简单应用程序(计算器)中的前导零问题。开始时零点打印在标签上,但是当我按下按钮时,例如" 1"我看到" 01"。它看起来并不好,所以我想改变它。我的代码如下。有人可以帮助我吗?

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=""
}

}

1 个答案:

答案 0 :(得分:0)

首先检查displayLabel.text的内容。如果是0,则只需将displayLabel.text设置为已按下的数字。另外,如果您在sender中声明buttonPressedUIButton,那么您就不必投出它:

@IBAction func buttonPressed(sender: UIButton) {
    let numb = sender.tag

    if displayLabel.text == "0" {
        displayLabel.text = "\(numb)"
    }
    else {
        displayLabel.text = "\(displayLabel.text!)\(numb)"
    }
}