X.BOZO X.BOZO - 7 months ago 31
Swift Question

How can I remove last typed digit from a UILabel?

If I type numbers in a label, and if it is a mistake,
how can I remove last typed digit from a UILabel ?

I already put a button for removing the last digit from the label.

The name of the button is back.

enter image description here

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet var lbltext: UILabel!
@IBOutlet var scrolview1: UIScrollView!
@IBOutlet var fi: UITextField!
@IBOutlet var scrolviewus: UIScrollView!
@IBOutlet var counterLabel: UILabel!
var isFirstTime = true

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

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


@IBAction func button(sender: AnyObject) {
lbltext.numberOfLines = 0
lbltext.text! = lbltext.text! + "\n" + fi.text! + "\n" + "---"
}

@IBAction func back(sender: AnyObject) {

}
}

Answer

Try this:

@IBAction func back(sender: AnyObject) {
    if let text = lbltext.text {
        lbltext.text = String(text.characters.dropLast())
    }
}

Since you want to remove more than just the last digit added, keep the previous state of your label in a property called previous, and just restore it when back is pressed:

var previous = ""

@IBAction func button(sender: AnyObject) {
    lbltext.numberOfLines = 0
    previous = lbltext.text!
    lbltext.text! = lbltext.text! + "\n" + fi.text! + "\n" + "---"
}

@IBAction func back(sender: AnyObject) {
    if !previous.isEmpty {
        lbltext.text = previous
        previous = ""
    }
}

For multiple levels of undo, use an array to hold your previous labels:

var previous: [String] = []

@IBAction func button(sender: AnyObject) {
    lbltext.numberOfLines = 0
    previous.append(lbltext.text!)
    lbltext.text = lbltext.text! + "\n" + fi.text! + "\n" + "---"
}

@IBAction func back(sender: AnyObject) {
    if let last = previous.last {
        lbltext.text = last
        previous.removeLast()
    }
}