如何编码连续添加数字的计算器(Swift)

时间:2014-09-28 22:20:03

标签: ios swift calculator

这是我的计算器代码,现在我只能在点击等号之前连续添加 2个数字,我想在哪里可以添加更多 <在点击等于按钮之前强>两个数字。 (以斯威夫特撰写)

import UIKit

class CalcControl: UIView {
var firstEntry = ""
var isUserInMiddleOfTypingNumbers:Bool?
var didUserPressedOperation:Bool?
var op:String?


@IBOutlet var displayLabel: UILabel!

@IBAction func digitPressed(sender: UIButton) {
    if (didUserPressedOperation == nil) {
        //displayLabel.text = ""
        didUserPressedOperation = nil
    }

    if (isUserInMiddleOfTypingNumbers == nil) {
        displayLabel.text = displayLabel.text! + sender.currentTitle!
    } else {
        displayLabel.text = sender.currentTitle
        isUserInMiddleOfTypingNumbers = true
    }
        }

@IBAction func operationPressed(sender: UIButton) {
    op = sender.currentTitle
    firstEntry = displayLabel.text!
    didUserPressedOperation = true
    displayLabel.text = ""


}

@IBAction func clearPressed(sender: UIButton) {
    self.clear()
}

func clear() {
    firstEntry = ""
    isUserInMiddleOfTypingNumbers = nil
    didUserPressedOperation = nil
    displayLabel.text = ""
}


@IBAction func equalPressed(sender: UIButton) {
    var secondEntry:NSString = displayLabel.text!
    println((firstEntry))
    println((secondEntry))

    if(op == "+") {
        displayLabel.text = (((firstEntry as NSString!).doubleValue + (secondEntry as NSString).doubleValue) as NSNumber).stringValue
    } else if(op == "-") {
        displayLabel.text = (((firstEntry as NSString!).doubleValue - (secondEntry as NSString).doubleValue) as NSNumber).stringValue
    } else if(op == "x") {
        displayLabel.text = (((firstEntry as NSString!).doubleValue * (secondEntry as NSString).doubleValue) as NSNumber).stringValue
    } else if(op == "/") {
        displayLabel.text = (((firstEntry as NSString!).doubleValue / (secondEntry as NSString).doubleValue) as NSNumber).stringValue
    }


    firstEntry = ""
    isUserInMiddleOfTypingNumbers = nil
    didUserPressedOperation = nil
}

   }

1 个答案:

答案 0 :(得分:1)

我会调整你的逻辑,以便:

  1. 有一个IB动作,所有操作员键(+, - ,x,/)都绑定到。在这个IB动作中,只要它被激活,有两种选择:a)准备输入另一个号码或b)前一个键序列是一个数字,后跟一个操作符号,按钮与Enter相同。 / p>

  2. 删除密钥的IB操作。显而易见的角色。

  3. Enter键的IB操作。