我今天已經花了一天時間來熟悉Swift,我決定嘗試構建一個計算器。我除了一個問題開展工作,整個事情:斯威夫特計算器可以完美的工作,但不會在執行新操作時出現
1 + 1將返回2標籤(這是罰款)
但是,當我嘗試鍵入一個新數字,例如1,字符串被追加到21,而不是清除標籤,並把奇異1
這是因爲我想添加的選項爲運營商不斷加入例如:
1 + 1返回2,則用戶類型+ 3得到5的結果
唯一的問題是我不知道如何清除標籤只有當等號被按下後輸入一個新號碼
這是視圖控制器的代碼希望我不必想到一個完全不同的方法。
import UIKit
class ViewController: UIViewController {
var num1 = ""
var num2 = ""
var finalString = ""
var isFirstNumber = true
var hasFinalString = false
var isClear = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBOutlet weak var LBLOutput: UILabel!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btrNumberClick(_ sender: UIButton) {
if isClear {
LBLOutput.text = ""
isClear = false
}
let currentText = LBLOutput.text!
let textLabel = sender.titleLabel?.text
if let text = textLabel {
switch text {
case "+", "x", "/", "-","%":
if hasFinalString {
return
}
finalString = text
isFirstNumber = false
hasFinalString = true
LBLOutput.text = "\(currentText) \(finalString) "
break
case "=":
isFirstNumber = true
hasFinalString = false
isClear = true
let result = calculate()
LBLOutput.text = "\(result)"
num1 = "\(result)"
break
default:
if isFirstNumber {
num1 = "\(num1)\(text)"
} else {
num2 = "\(num2)\(text)"
}
LBLOutput.text = "\(currentText)\(text)"
break;
}
}
}
func calculate() -> Double {
let firstNumber = Double(num1)!
let secondNumber = Double(num2)!
num1 = ""
num2 = ""
isClear = false
switch finalString {
case "+":
return firstNumber + secondNumber
case "-":
return firstNumber - secondNumber
case "x":
return firstNumber * secondNumber
case "/":
return firstNumber/secondNumber
case "%":
return (firstNumber * 100)/secondNumber
default:
return 0
}
}
@IBAction func clearTheLabel(_ sender: Any) {
num1 = ""
num2 = ""
LBLOutput.text = "0"
isClear = true
}
}
備註:我建議爲每個按鈕創建一個IBAction,而不是將所有按鈕連接到相同的IBAction並通過其文本識別它,這將更具可讀性,甚至更有效。 –