我的简单应用程序(计算器)中的前导零问题。开始时零点打印在标签上,但是当我按下按钮时,例如" 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=""
}
}
答案 0 :(得分:0)
首先检查displayLabel.text
的内容。如果是0
,则只需将displayLabel.text
设置为已按下的数字。另外,如果您在sender
中声明buttonPressed
为UIButton
,那么您就不必投出它:
@IBAction func buttonPressed(sender: UIButton) {
let numb = sender.tag
if displayLabel.text == "0" {
displayLabel.text = "\(numb)"
}
else {
displayLabel.text = "\(displayLabel.text!)\(numb)"
}
}