Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
At times you want to ensure that a user enters only a certain subset of characters. For example, you might want to create a numeric-only text field that does not handle letters. Although you can use predicates to test the final entry against a regular expression (the NSPredicate class’s MATCH operator supports regex values, and is demonstrated in Recipe 10-10), for filtered data it’s easier to check each new character as it’s typed against a legal set.
A UITextField delegate can catch those characters as they are typed and decide whether to add the character to the active text field. The optional textField:shouldChangeCharactersInRange:replacementString: delegate method returns either YES, allowing the newly typed character(s), or NO, disallowing it (or them). In practice, this works on a character-by-character basis being called after each user keyboard tap. However, with iOS’s pasteboard support, the replacement string could theoretically be longer when text is pasted to a text field.