简体   繁体   English

如何在Swift中从UI标签中删除字符?

[英]How to delete a character from a UI Label in Swift?

I am new to Swift and I am having issues with deleting a character from a UI Label that I have created. 我是Swift的新手,从创建的UI标签中删除字符时遇到问题。 I am trying to make a simple phone dailer app, and I am trying ti implement a backspace button. 我正在尝试制作一个简单的电话dailer应用程序,并且正在尝试实施一个退格按钮。 My UI Label is called DailerLabel, and I know I'm supposed to use the dropLast() function but I keep running into issues about mismatching types or unwrappers. 我的UI标签称为DailerLabel,我知道我应该使用dropLast()函数,但是我一直遇到有关类型不匹配或解包的问题。 I am not really sure what I am supposed to do here. 我不确定我应该在这里做什么。 I tried the thing in the commented code which didn't work, and then I tried what I listed below which doesn't either. 我在注释的代码中尝试了无效的东西,然后又尝试了下面列出的方法,但均无效。 Could anyone help me? 有人可以帮我吗?

    @IBAction func backspaceButtonPressed(_ sender: UIButton) {
    if (!((DailerLabel.text?.isEmpty)!)) {

       // DailerLabel.text?.substring(to: (DailerLabel.text?.index(before: (DailerLabel.text?.endIndex)!))!)

        let temp = DailerLabel.text
        temp?.dropLast()
        DailerLabel.text = temp

    }

You can try this one, replace label with your own UILabel 您可以尝试一下,用自己的UILabel替换标签

var name: String = label.text! //shauket , for example 
name.remove(at: name.index(before: name.endIndex))
print(name)    //shauke

label.text = name
print(label.text!)

You are very close. 你很亲密 dropLast actually returns the string without the last character and you haven't stored that to anything so there is no change. dropLast实际上返回不带最后一个字符的字符串,并且您尚未将其存储到任何内容,因此没有变化。 You also have to conver back to String from Substring. 您还必须从子字符串转换回字符串。

@IBAction func backspaceButtonPressed(_ sender: UIButton) {
    if (!((DailerLabel.text?.isEmpty)!)) {
        let temp = DailerLabel.text ?? ""
        DailerLabel.text = String(temp.dropLast())
    }
}

Here's a better version 这是一个更好的版本

@IBAction func backspaceButtonPressed(_ sender: UIButton) {
    guard
        let text = dialerLabel.text,
        !text.isEmpty
    else {
        return
    }
    dialerLabel.text = String(text.dropLast())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM