Recipe: Text-Entry Filtering

You might sometimes 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 6-10), for filtered data, it’s easier to check each new character as it is typed against a legal set.

A UITextField delegate can catch those characters as they are typed and decide whether to add each character to the active text field. The optional textField:shouldChangeCharactersInRange:replacementString: delegate method returns either YES, allowing the newly ...

Get The Core iOS Developer’s Cookbook, Fifth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.