'swift - Remove white spaces from var(UITextField input) doesn't work
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!
Solution 1:[1]
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)
Solution 2:[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
}
Solution 3:[3]
For Swift 3 you can use:
//let myTextField.text = " Hello World"
myTextField.text.replacingOccurrences(of: " ", with: "")
// Result: "Helloworld"
Solution 4:[4]
let string = textField.text?.trimmingCharacters(in: .whitespaces)
Solution 5:[5]
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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Anbu.Karthik |
Solution 2 | Alessandro Ornano |
Solution 3 | gandhi Mena |
Solution 4 | nslllava |
Solution 5 | Neha |