I want to restrict the use of the spacebar in the beginning of the textfield in iOS. I tried to use the below logic but it is not allowing spaces anywhere between the words. Please help me in this case.
if self.rangeOfCharacterFromSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) != nil {
return false
}
return true
If you need to do what you described, you can use the textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String)
method in UITextViewDelegate
.
Example:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
// as @nhgrif suggested, we can skip the string manipulations if
// the beginning of the textView.text is not touched.
guard range.location == 0 else {
return true
}
let newString = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text) as NSString
return newString.rangeOfCharacterFromSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).location != 0
}
First, we construct the new string that will be shown in the textView
.
And then we check if it start with a whitespace, tab or newline character.
If so, we return false
so the the textView
won't place the new text in.
Otherwise, put the new text into the textView
.
Note: We need to check the whole string instead of checking the replacementText
to deal with copy-paste actions.
Another possible way is not restricting the text the user typed, but trimming the result text when you need to use the value.
let myText = textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
Edit: add a guard
clause to make the method more performant based on @nhgrif's comment.