Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop the user not to type space in the beginning of the text in UITextView iOS?

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
like image 223
coolly Avatar asked Oct 25 '25 10:10

coolly


2 Answers

For TextField

Swift 5.2, Xcode 11.4

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard range.location == 0 else {
        return true
    }

    let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string) as NSString
    return newString.rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines).location != 0
}
like image 51
Kedar Sukerkar Avatar answered Oct 28 '25 01:10

Kedar Sukerkar


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.

like image 42
Cheng-Yu Hsu Avatar answered Oct 27 '25 23:10

Cheng-Yu Hsu