我正在尝试让标签显示数字和运算符(加号或减号或其他)和下一个数字,然后用户点击结果的等号。我得到的是第一个数字,然后当操作员被点击时(仅用加号测试),第一个数字从屏幕上删除,并在被点击时被操作符号和第二个数字替换。
有人可以帮我看看我做错了什么吗?这是我有史以来的第一个Swift项目。
class ViewController: UIViewController {
@IBOutlet weak var outputLbl: UILabel!
var runningNumber = ""
var leftValue = ""
var rightValue = ""
var result = ""
var currentOperation:Operation = .NULL
override func viewDidLoad() {
super.viewDidLoad()
outputLbl.text = "0"
}
@IBAction func numberPressed(_ sender: RoundButton) {
if runningNumber.count <= 8 {
runningNumber += "\(sender.tag)"
outputLbl.text = runningNumber
}
}
@IBAction func allClearPressed(_ sender: RoundButton) {
runningNumber = ""
leftValue = ""
rightValue = ""
result = ""
currentOperation = .NULL
outputLbl.text = "0"
}
@IBAction func dotPressed(_ sender: RoundButton) {
if runningNumber.contains(".") {
} else {
runningNumber += "."
outputLbl.text = runningNumber
}
}
@IBAction func equalPressed(_ sender: RoundButton) {
operation(operation: currentOperation)
}
@IBAction func addPressed(_ sender: RoundButton) {
operation(operation: .Add)
runningNumber += "\("+")"
outputLbl.text = runningNumber
}
@IBAction func subtractPressed(_ sender: RoundButton) {
operation(operation: .Subtract)
}
@IBAction func multiplyPressed(_ sender: RoundButton) {
operation(operation: .Multiply)
}
@IBAction func dividePressed(_ sender: RoundButton) {
operation(operation: .Divide)
}
func operation (operation:Operation){
if currentOperation != .NULL{
if runningNumber != ""{
rightValue = runningNumber
runningNumber = ""
if currentOperation == .Add{
result = "\(Double(leftValue)! + Double(rightValue)!)"
} else if currentOperation == .Subtract{
result = "\(Double(leftValue)! - Double(rightValue)!)"
} else if currentOperation == .Multiply{
result = "\(Double(leftValue)! * Double(rightValue)!)"
} else if currentOperation == .Divide{
result = "\(Double(leftValue)! / Double(rightValue)!)"
}
leftValue = result
if (Double(result)!.truncatingRemainder(dividingBy: 1) == 0){
result = "\(Int(Double(result)!))"
}
outputLbl.text = result
}
currentOperation = operation
} else {
leftValue = runningNumber
runningNumber = ""
currentOperation = operation
}
}
}
答案 0 :(得分:0)
当您致电func addPressed
时,第一个功能operation(operation: .Add)
正在将您的runningNumber
设置为空字符串值""
。之后,runningNumber += "\("+")"
被称为为您提供"" + "\("+")"
的内容,这就是您的标签向您展示运营商的原因。这意味着逻辑有点破碎。您不应重置runningNumber
值,或者可能添加某种保存输出字符串值的变量。
另外,我建议您优化代码,而不是使用func operation(operation: Operation)
中的switch-case而不是多个if-else语句。可以帮助您提高代码的可读性。