DeZigny
DeZigny

Reputation: 1953

Xcode: How to allow only certain characters in UITextView?

How to allow only certain characters in UITextView?

I want to allow only English characters & numbers & Arabic characters.

I found many solutions but for UITextField not UITextView!

Upvotes: 0

Views: 698

Answers (1)

Jonathan
Jonathan

Reputation: 6732

You can use the textView:shouldChangeTextInRange:replacementText: method of the UITextViewDelegate (docs):

The text view calls this method whenever the user types a new character or deletes an existing character. Implementation of this method is optional. You can use this method to replace text before it is committed to the text view storage. For example, a spell checker might use this method to replace a misspelled word with the correct spelling.

You should check if the replacementText parameter contains illegal characters. In that case you can return NO to prevent the text from being inserted. This might give problems when a text of more than one character is inserted, and not all characters are allowed: what do you do, allow the insertion (including the illegal characters) or prevent it (including the allowed characters)?


This means you need the textViewDidChange: method (docs):

The text view calls this method in response to user-initiated changes to the text. This method is not called in response to programmatically initiated changes.

When this method is called you could check the value of the UITextView and remove illegal characters afterwards.


I think it would be best to use both methods. The first one gives the best experience when the user is typing (the character is not displayed at all, instead of first being displayed and later being removed). The second method makes sure that illegal characters will be removed if some text is pasted, for example.

Upvotes: 2

Related Questions