Please note, this blog entry is from a previous course. You might want to check out the current one.
Implement a “backspace” button for the user to touch if they hit the wrong digit button. This is not intended to be “undo,” so if the user hits the wrong operation button, he or she is out of luck! It is up to you to decide how to handle the case where the user backspaces away the entire number they are in the middle of typing, but having the display go completely blank is probably not very user-friendly.
Change the label of one of the “invisible” buttons to “BS”:
Link the “new” button to a new action. If the user is in the middle of typing a number, and there is more than one character remove the last one, otherwise set the display to zero:
@IBAction func backSpace() { if userIsInTheMiddleOfTypingANumber { let displayText = display.text! if countElements(displayText) > 1 { display.text = dropLast(displayText) } else { display.text = "0" } } }
The complete code for extra task #1 is available on GitHub.
(Italiano) BS non funziona se display.text contiene il risultato di un’operazione. Forse è meglio farlo funzionare anche in quel caso. Allora il metodo backSpace è anche più semplice:
(English) BS does not work if display.text contains the result of an operation. Perhaps it is better to make it work even then. Then the method Backspace is even simpler:
@IBAction func backSpace() {
if countElements(display.text!) > 1 {
display.text = dropLast(display.text!)
} else {
display.text = “0”
}
}
Backspace is only supposed to work when the user is in the middle of typing a number. That’s the task …
Don’t you have to reset userIsInTheMiddleOfTypingANumber flag to false case you set display.text to “0”?