Search code examples
iosswiftuibuttonibaction

Update label when clicked


I have code for running the history in the application.

How can I improve it so that the numbers are displayed immediately when pressed, and not just by pressing =?

My programm:

 // Connected to button "="
@IBAction func equalitySignPressed(sender: UIButton) {
  if stillTyping {
     secondOperand = currentInput
  }
dotIsPlaced = false

addHistory(text: operationSign + displayResultLabel.text!)

switch operationSign {
   case "+":
      operateWithTwoOperands{$0 + $1}
   case "-":
      operateWithTwoOperands{$0 - $1}
   case "×":
      operateWithTwoOperands{$0 * $1}
   case "÷":
      operateWithTwoOperands{$0 / $1}
default: break
  }
}
func addHistory(text: String){
     //Add text
    resultLabelText.text =  resultLabelText.text! + "" + text
}

Current Output:

enter image description here gif


Solution

  • You can use Key-Value observing(KVO) here.

    addObserver(self, forKeyPath: #keyPath(INPUTS), options: [.old, .new], context: nil)
    

    You can observer the value as

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == #keyPath(INPUT) {
            // Update UI
            resultLabelText = "NEW_VALUE"
        }
    }