0

我的简单应用程序(计算器)中的前导零有问题。开始时标签上打印零,但是当我点击按钮例如“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=""
}

}
4

1 回答 1

0

首先检查内容displayLabel.text。如果是0,则只需设置displayLabel.text为按下的数字。此外,如果您声明senderinbuttonPressed为 a UIButton,那么您不必强制转换它:

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

    if displayLabel.text == "0" {
        displayLabel.text = "\(numb)"
    }
    else {
        displayLabel.text = "\(displayLabel.text!)\(numb)"
    }
}
于 2015-10-23T17:07:16.780 回答