4

I'm new to swift, but from ObjectiveC background, I tried to get an input from textfield into a var, on a button click.

Now, when I tried to remove blank space using "stringByTrimmingCharactersInSet" and so many other options, it's not working. Here is my code,

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

    }

I also tried by assigning the result to a new var,

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

but still couldn't remove the whitespace. My guess is I'm confusing with the "Unwrapped value" concept, it'll be really helpful if someone could help me out. Thanks!

Rajesh S
  • 133
  • 1
  • 9
  • 1
    If you look at the docs, `someVariable.stringByTrimmingCharactersInSet ` returns a new string made by removing from both ends of the String characters contained in a given character set, so it's working as intended - see @Anbu's answer – sschale Apr 28 '16 at 07:12

5 Answers5

5

try the alternate way

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

or else try this

let trimmed = "".join(urlInputComponent.text!.characters.map({ $0 == " " ? "" : String($0) }))
 print (trimmed)
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
2

This is the code you can use to start the cleaning:

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

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

Add also this delegate method to your code:

 func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
       if range.location == 0 && string == " " {
           return false
       }
       return true
 }
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
2

For Swift 3 you can use:

//let myTextField.text = " Hello World"

myTextField.text.replacingOccurrences(of: " ", with: "")
// Result: "Helloworld"
gandhi Mena
  • 2,115
  • 1
  • 19
  • 20
2
let string = textField.text?.trimmingCharacters(in: .whitespaces)
nslllava
  • 589
  • 2
  • 9
  • 19
0

You can do it while typing in TextFeild

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