Limit the length of UITextField input.
I. Preface
For example, I can only enter 11 characters in textfield. If I enter more characters, only 11 characters in textfield will be displayed.
If ReactiveCocoa is used, this is a good solution. However, this class library is not introduced in the project, so it can only be obtained manually.
II. Implementation Principle
First look at the Code:
/// ViewController. m // Test /// Created by zhanggui on 15/12/28. // Copyright©2015 zhanggui. all rights reserved. // # import "ViewController. h "@ interface ViewController () @ property (weak, nonatomic) IBOutlet UITextField * myTextField; @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; [[nsicationcenter center defacenter center] addObserver: self selector: @ selector (textFiledEditChanged :) name: @ "UITextFieldTextDidChangeNotification" object: self. myTextField]; self. myTextField. placeholder = @ "only 11 digits can be entered."; // Do any additional setup after loading the view, typically from a nib .} # pragma mark-UITextFieldDelegate-(void) textFiledEditChanged :( NSNotification *) obj {UITextField * textField = (UITextField *) obj. object; NSString * toBeString = textField. text; if (toBeString. length-1> 10 & toBeString. length> 1) {textField. text = [toBeString substringToIndex: 11] ;}}@ end
The procedure is as follows:
First, we need to add a notification whose name is UITextFieldTextDidChangeNotification. We can click this name to see
UIKIT_EXTERN NSString *const UITextFieldTextDidChangeNotification;
This is a constant string defined in UITextField. h. Its function is as follows:
The content in the textField of the notification observer changes, and the affected textField is stored in the object parameter of the notification. (Notifies observers that the text in a text field changed. The affected text field is stored in the object parameter of the notification .)
In this way, we can control it through notifications. Every time we input a character in textField, we will listen in the notification method. I will judge whether the length of the input string meets the required conditions, if the conditions are met (the condition here is 11 bits), The textField text will always be equal to the length I want to limit. To fulfill your needs.