当我按+或-(​​Swift5)时计算器没有清除标签吗?

时间:2019-06-15 01:00:41

标签: swift

当我按+-标签时无法清除 标签屏幕上的上一个号码。

import UIKit

enum modes {
    case not_set
    case addition
    case subtraction

}

class ViewController: UIViewController {
    @IBOutlet weak var label: UILabel!

    var labelString:String = "0"
    var currentMode:modes = .not_set
    var savedNum:Int = 0
    var previousNumber: Double = 0
    var lastButtonWasMode:Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated
    }


    @IBAction func plusButton(_ sender: Any) {

        changeModes(newMode: .addition)

    }

    @IBAction func minusButton(_ sender: Any) {
        changeModes(newMode: .subtraction)
    }

    @IBAction func equalsButton(_ sender: Any) {

    }

    @IBAction func clearButton(_ sender: Any) {
        labelString = "0"
        currentMode = .not_set
        savedNum = 0
        lastButtonWasMode = false
        label.text = "0"
    }

    @IBAction func pressNumber(_ sender: UIButton) {
        let stringValue:String? = sender.titleLabel?.text

        labelString = labelString.appending(stringValue!)
        updateText()
        if(lastButtonWasMode) {

            lastButtonWasMode = false
            labelString = "0"
        }

    }

    func updateText() {
        guard let labelInt:Int = Int(labelString) else {
            return
        }
        if (currentMode == .not_set) {
            savedNum = labelInt
        }

        label.text = "\(labelInt)"
    }
    func changeModes(newMode:modes) {
        if (savedNum == 0) {
            return
        }

        currentMode = newMode
        lastButtonWasMode = true
    }
}

当我按+-x时如何清除主屏幕(标签)?

1 个答案:

答案 0 :(得分:0)

当您在操作后键入第一位数字时,计算器通常会清除显示。将属性添加到您的ViewController

var enteringANumber = false

plusButton()minusButton()equalButton()clearButton()中,将enteringANumber设置为false

然后在pressNumber中进行检查:

@IBAction func pressNumber(_ sender: UIButton) {
    let stringValue = sender.titleLabel?.text

    if !enteringANumber {
        labelString = ""
        enteringANumber = true
    }

    ...
}