試圖讓我的清除按鈕能夠工作,但作爲新鮮的程序員,我仍然有一些邏輯發現問題。 計算器工作完美,但是當我按下清除任何id發生。計算器中的清除按鈕沒有響應
class ViewController: UIViewController {
enum Operation: String {
case Divide = "/"
case Multiply = "*"
case Subtract = "-"
case Add = "+"
case Empty = "Empty"
}
@IBOutlet weak var outputLbl: UILabel!
var btnSound: AVAudioPlayer!
var runningNumber = ""
var leftValStr = ""
var rightValStr = ""
var currentOperation: Operation = Operation.Empty
var result = ""
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("btn", ofType: "wav")
let soundUrl = NSURL(fileURLWithPath: path!)
do{
try btnSound = AVAudioPlayer(contentsOfURL: soundUrl)
btnSound.prepareToPlay()
} catch let err as NSError{
print(err.debugDescription)
}
}
@IBAction func numberPressed(btn: UIButton!){
playSound()
runningNumber += "\(btn.tag)"
outputLbl.text = runningNumber
}
@IBAction func onDividePressed(sender: AnyObject) {
processOperation(Operation.Divide)
}
@IBAction func onMultiplyPressed(sender: AnyObject) {
processOperation(Operation.Multiply)
}
@IBAction func onSubtractPressed(sender: AnyObject) {
processOperation(Operation.Subtract)
}
@IBAction func onAddPressed(sender: AnyObject) {
processOperation(Operation.Add)
}
@IBAction func onEqualPressed(sender: AnyObject) {
processOperation(currentOperation)
}
@IBAction func onClearPressed(sender: AnyObject) {
processOperation(Operation.Empty)
}
func processOperation(op: Operation) {
playSound()
if currentOperation != Operation.Empty{
//run math
//a user selected an operator, but then selected another operator without
//first entering a number
if runningNumber != ""{
rightValStr = runningNumber
runningNumber = ""
if currentOperation == Operation.Multiply{
result = "\(Double(leftValStr)! * Double(rightValStr)!)"
} else if currentOperation == Operation.Divide{
result = "\(Double(leftValStr)!/Double(rightValStr)!)"
} else if currentOperation == Operation.Subtract{
result = "\(Double(leftValStr)! - Double(rightValStr)!)"
} else if currentOperation == Operation.Add{
result = "\(Double(leftValStr)! + Double(rightValStr)!)"
} else if currentOperation == Operation.Empty{
result = ""
outputLbl.text = result
}
leftValStr = result
outputLbl.text = result
}
currentOperation = op
}else{
//first time its been pressed
leftValStr = runningNumber
runningNumber = ""
currentOperation = op
}
}
func playSound() {
if btnSound.playing{
btnSound.stop()
}
btnSound.play()
}
}
非常感謝! 不得不做出一些tweek:d outputLbl.text =「0」 現在,當我按下清除按鈕將其重置並設置計算器0 – Koljane
會做的那一刻我賺15爬行點:d – Koljane