コードで私は解決しようとしているがまだ解決策を見つけられていない小さな問題です。
このコードは計算機用です。
正しい計算をしています。
しかし、私は "クリア"ボタンを押すと、新しい計算の前に "0"のままです。
例:「クリア」と「2」の後に入力します。画面に "02"と表示されます。
誰かがコードを見て解決策を見たら非常に感謝します。スイフト電卓。 "0"が画面に残ります
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var outputLbl: UILabel!
var btnSound: AVAudioPlayer!
@IBAction func clearBtnPressed(_ sender: Any) {
playSound()
runningNumber = ""
leftValStr = ""
outputLbl.text = ""
currentOperation = Operation.Empty
}
enum Operation: String {
case Divide = "/"
case Multiply = "*"
case Subtract = "-"
case Add = "+"
case Empty = "Empty"
}
var currentOperation = Operation.Empty
var runningNumber = ""
var leftValStr = ""
var rightValStr = ""
var result = ""
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.path(forResource: "btn", ofType: "wav")
let soundURL = URL(fileURLWithPath: path!)
do {
try btnSound = AVAudioPlayer(contentsOf: soundURL)
btnSound.prepareToPlay()
} catch let err as NSError {
print(err.debugDescription)
}
outputLbl.text = ""
}
@IBAction func numberPressed(sender: UIButton) {
playSound()
runningNumber += "\(sender.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(operation: currentOperation)
}
func playSound() {
if btnSound.isPlaying {
btnSound.stop()
}
btnSound.play()
}
func processOperation(operation: Operation) {
playSound()
if currentOperation != Operation.Empty {
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)!)"
}
leftValStr = result
outputLbl.text = result
}
currentOperation = operation
} else {
leftValStr = runningNumber
runningNumber = ""
currentOperation = operation
}
}
}
あなたの数値に条件を追加します。それが何であれ== "0"であればそれを置き換えますそれ以外の場合は文字列に追加します –
'0'は' clear'を押した後にどこから来ますか?数字の追加時に数字ではなくテキストを扱っているので、先行ゼロが残っています。 – vadian