Шаг 1. Создайте класс, реализующий протокол UITextFieldDelegate
@interface TheDelegateClass : NSObject <UITextFieldDelegate>
Шаг 2. В своей реализации переопределите метод - (BOOL) textField: (UITextField *) textField shouldChangeCharactersInRange: (NSRange) range replaceString: (NSString *) string
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// newString is what the user is trying to input.
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ([newString length] < 1) {
// If newString is blank we will just ingore it.
return YES;
} else
{
// Otherwise we cut the length of newString to 1 (if needed) and set it to the textField.
textField.text = [newString length] > 1 ? [newString substringToIndex:1] : newString;
// And make the keyboard disappear.
[textField resignFirstResponder];
// Return NO to not change text again as we've already changed it.
return NO;
}
}
Шаг 3: Установить экземпляр класса делегата в качестве делегата UITextField.
TheDelegateClass *theDelegate = [[TheDelegateClass alloc] init];
[theTextField setDelegate:theDelegate];