计算器swift2中的前导零
Leading zero in calculator swift2
我的简单应用程序(计算器)中有前导零问题。开始时,标签上印有零,但是当我点击按钮(例如“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=""
}
}
先检查displayLabel.text
的内容。如果是0
,那么只需将displayLabel.text
设置为按下的数字即可。此外,如果您将 buttonPressed
中的 sender
声明为 UIButton
,那么您不必强制转换它:
@IBAction func buttonPressed(sender: UIButton) {
let numb = sender.tag
if displayLabel.text == "0" {
displayLabel.text = "\(numb)"
}
else {
displayLabel.text = "\(displayLabel.text!)\(numb)"
}
}
我的简单应用程序(计算器)中有前导零问题。开始时,标签上印有零,但是当我点击按钮(例如“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=""
}
}
先检查displayLabel.text
的内容。如果是0
,那么只需将displayLabel.text
设置为按下的数字即可。此外,如果您将 buttonPressed
中的 sender
声明为 UIButton
,那么您不必强制转换它:
@IBAction func buttonPressed(sender: UIButton) {
let numb = sender.tag
if displayLabel.text == "0" {
displayLabel.text = "\(numb)"
}
else {
displayLabel.text = "\(displayLabel.text!)\(numb)"
}
}