如何从UILabel中删除最后输入的数字?

时间:2016-05-07 09:53:56

标签: ios swift swift2.2

如果我在标签上输入数字,如果是错误, 如何从UILabel中删除最后输入的数字?

我已经放了一个按钮来删除标签上的最后一位数字。

按钮的名称是 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) {

    }
}

5 个答案:

答案 0 :(得分:3)

Objective-c

label.text = [label.text stringByReplacingCharactersInRange:NSMakeRange(label.text.length - 1, 1) withString:@""];

斯威夫特

    if let text = label.text{
            let nsRange : NSRange = NSRange(location: (text.characters.count) - 1, length: 4)

            label.text = (label.text! as NSString)
                .stringByReplacingCharactersInRange(nsRange, withString: "")

    }

答案 1 :(得分:3)

试试这个:

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

由于您要删除的不仅仅是添加的最后一个数字,请将标签的先前状态保留在名为previous的属性中,并在按下 back 时将其恢复:

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 = ""
    }
}

对于多个撤消级别,请使用数组来保存以前的标签:

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()
    }
}

答案 2 :(得分:2)

 let name: String = self.display.text!
 let stringLength = count(name)
 let substringIndex = stringLength - 1
 lbltext.text = (name as NSString).substringToIndex(substringIndex)

答案 3 :(得分:1)

你刚试过代表shouldChangeCharactersInRange吗? :

请记住在 viewDidLoad

下进行
HtmlDocument

然后致电代表:

fi.delegate = self

答案 4 :(得分:1)

@IBAction func back(sender: AnyObject) {
        for var i:Int = 0 ; i < 4 ; i++
        {
            if let text = lbltext.text 
            {
                lbltext.text = String(text.characters.dropLast())
            }
        }
    }