初階計算機

已經有Auto Layout了

先上動圖:

這次程式碼比較多一點

也有很多可以延伸的功能

//列舉各種算法
enum
OperationType{
case addcase subtractcase multiplycase dividecase none}class ViewController: UIViewController {@IBOutlet weak var label: UILabel!//此變數儲存(運算之前)畫面上的數字 先存入0var previousNumber:Double = 0//此變數儲存(當前)畫面上的數字 原始值0 所以存入0var numberOnScreen:Double = 0//此變數儲存是不是在運算的過程中 一開始不是所以falsevar performingMath = false//此變數儲存當下是何種運算 一開始都沒有所以nonevar operation:OperationType = .none//此變數來判斷是否重啟運算 把該答案數字直接替換成新輸入的數字var startNew = trueoverride var preferredStatusBarStyle: UIStatusBarStyle{return .lightContent}//加法@IBAction func add(_ sender: UIButton) {label.text = "+"operation = .add//是運算中performingMath = truepreviousNumber = numberOnScreen}//減法@IBAction func subtract(_ sender: UIButton) {label.text = "-"operation = .subtract//是運算中performingMath = truepreviousNumber = numberOnScreen}//乘法@IBAction func multiply(_ sender: UIButton) {label.text = "x"operation = .multiply//是運算中performingMath = truepreviousNumber = numberOnScreen}//除法@IBAction func divide(_ sender: UIButton) {label.text = "/"operation = .divide//是運算中performingMath = truepreviousNumber = numberOnScreen}//設定C 清除鍵 且將所有的值回歸初始值@IBAction func clearC(_ sender: UIButton) {label.text = "0"//此變數儲存畫面上的數字 原始值0 所以存入0numberOnScreen = 0//此變數儲存畫面運算之前畫面上的數字 先存入0previousNumber = 0//此變數儲存是不是在運算的過程中 一開始不是所以falseperformingMath = false//此變數儲存是如何的運算 一開始都沒有所以noneoperation = .nonestartNew = true}//讓文字標籤顯示正確 沒有.0func makeOKNumberString(from number:Double){var okText:Stringif floor(number) == number{okText = "\(Int(number))"}else{okText = "\(number)"}if okText.count >= 10{//就取前面10個數字okText = String(okText.prefix(10))}label.text = okText}@IBAction func giveMeAnswer(_ sender: UIButton) {//是運算中if performingMath == true{switch operation{case .add:numberOnScreen = previousNumber + numberOnScreenmakeOKNumberString(from: numberOnScreen)case .subtract:numberOnScreen = previousNumber - numberOnScreenmakeOKNumberString(from: numberOnScreen)case .multiply:numberOnScreen = previousNumber * numberOnScreenmakeOKNumberString(from: numberOnScreen)case .divide:numberOnScreen = previousNumber / numberOnScreen//驗證該答案數字是不是有小數makeOKNumberString(from: numberOnScreen)case .none:label.text = "0"}performingMath = falsestartNew = true}}//按到任一數字的方法@IBAction func numbers(_ sender: UIButton) {//判斷選到的數字 要-1因為先前有在按鍵Tag設定多1let inputnumber = sender.tag - 1if label.text != nil{if startNew == true{label.text = "\(inputnumber)"startNew = false}else{if label.text == "0" || label.text == "+" || label.text == "-" || label.text == "x" || label.text == "/"{label.text = "\(inputnumber)"}else{label.text = label.text! + "\(inputnumber)"}}numberOnScreen = Double(label.text!) ?? 0}}

--

--