swift - 从 var(UITextField 输入) 中删除空格不起作用

swift - Remove white spaces from var(UITextField input) doesn't work

我是 swift 的新手,但在 ObjectiveC 背景下,我尝试通过单击按钮将文本字段中的输入输入到 var 中。

现在,当我尝试使用 "stringByTrimmingCharactersInSet" 和许多其他选项删除空白 space 时,它不起作用。这是我的代码,

    var someVariable = urlInputComponent.text!
    if someVariable.containsString(" "){
        someVariable = someVariable.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        print(someVariable)

    }

我也尝试过将结果分配给一个新的变量,

        let trimmed: String = someVariable.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        print(trimmed)

但仍然无法去除白色space。我的猜测是我对 "Unwrapped value" 概念感到困惑,如果有人能帮助我,那将非常有帮助。谢谢!

试试其他方法

 urlInputComponent.text! = urlInputComponent.text!.stringByReplacingOccurrencesOfString(" ", withString: "")

或者试试这个

let trimmed = "".join(urlInputComponent.text!.characters.map({ [=11=] == " " ? "" : String([=11=]) }))
 print (trimmed)

这是您可以用来开始清洁的代码:

extension String {
    func condenseWhitespace() -> String {
        let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!Swift.isEmpty([=10=])})
        return " ".join(components)
    }
}

var string = "  Lorem   \r  ipsum dolar   sit  amet. "
println(string.condenseWhitespace())

还将此委托方法添加到您的代码中:

 func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
       if range.location == 0 && string == " " {
           return false
       }
       return true
 }

对于Swift 3你可以使用:

//let myTextField.text = " Hello World"

myTextField.text.replacingOccurrences(of: " ", with: "")
// Result: "Helloworld"
let string = textField.text?.trimmingCharacters(in: .whitespaces)

您可以在 TextField 中键入时执行此操作

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == " " {
            textField.text = textField.text!.replacingOccurrences(of: " ", with: "")
            return false
        }
    return true
}