The length of UITextField is limited.
Restrict UITextField input length
Tags (separated by spaces): UITextField
UITextField is one of the most common components in iOS. It also has various requirements, which are not provided with corresponding APIs. Limit the text length of an input box is a common requirement. UITextField does not provide APIs for this purpose. This article attempts to add this function to it.
1. Implemented through delegate (not recommended)
Limit the number of UITextField inputs.UITextFieldDelegate
To implement this Protocol:
-(BOOL) textField :( UITextField *) textField shouldChangeCharactersInRange :( nsange) range replacementString :( NSString *) string; // NO text will be changed if NO is returned.
OK, let's try:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *beString = [textField.text stringByReplacingCharactersInRange:range withString:string]; if ([beString length] > 20) { textField.text = [beString substringToIndex:20]; return NO; } return YES;}
1. Calculate the new text: beString generated by the user input.
2. Determine whether the beString length meets the length limit (20 here ).
3. If YES, YES is returned; otherwise, NO is returned.
OK. This achieves our needs and runs correctly in a variety of input methods, both Chinese and English. Is this all done? NO!
Let's talk about the shortcomings of this solution:
1. Too much code. Let's take a look at the example above. This is just an input box. If there are 2, 3, or N... (You have to reconsider your requirements)
2. I have to write this for every input box to limit the length. I think it is also drunk (Yes, I used to do this too ).
2. inherit UITextField (not recommended)
Inherit UITextField and overwritesetText:
The method should be feasible (I have never done it ). However, based on the experience of countless elders, the combination prevails over inheritance. Inheritance is also a small problem here: Suppose our subclass name isNLUITextFieldTextLimit
, ThatNITextField
(A class in the nimbus framework) Objects cannot enjoy this service.
3. Add attributes for classification (recommended)
If you can use classification, it would be nice to add an attribute to achieve this requirement.UITextField
Define an attribute in. Let's study it.UITextField
See if it is possible.
@interface UITextField : UIControl...
UITextField
Is inherited fromUIControl
So it can listen to its own events! Good! We only need to know that the input text changes, and then determine whether the length meets the requirements. Let's look at our code:
//. H file @ interface UITextField (NLLimit) @ property (assign, nonatomic) NSUInteger nl_maxLength; @ end //. m file # import <objc/runtime. h> @ implementation UITextField (NLLimit) static void * Signature = & signature;-(void) setNl_maxLength :( NSUInteger) nl_maxLength {signature (self, signature, @ (nl_maxLength), OBJC_ASSOCIATION_COPY ); /*** monitor text changes */if (nl_maxLength> 0) {[self addTarget: self action: @ selector (_ nl_valueChanged :) forControlEvents: UIControlEventAllEditingEvents];} else {[self removeTarget: self action: @ selector (_ nl_valueChanged :) forControlEvents: role] ;}}-(NSUInteger) nl_maxLength {return [transform (self, assign) unsignedIntegerValue];} # pragma mark-private-(void) _ nl_valueChanged :( UITextField *) textField {/*** determine whether the text length meets the requirement after the text changes */if (self. nl_maxLength = 0) return; if ([textField. text length] <= self. nl_maxLength) return; NSString * subString = [textField. text substringToIndex: self. nl_maxLength]; dispatch_async (dispatch_get_main_queue (), ^ {textField. text = subString; [textField sendActionsForControlEvents: UIControlEventEditingChanged];}) ;}@ end
The code is here.
Well, it's simple and straightforward!
4. Restrict the UITextView input length
InUITextField
We recommend that you add attributes to the classification to limit the text length. In essence, you can monitor your input text changes and determine whether the length meets your requirements. ThatUITextView
Can we do the same?
@interface UITextView : UIScrollView
Unfortunately, as shown above,UITextView
YesUIScrollView
NotUITextField
That isUIControl
That isUITextView
Not likeUITextField
In this way, we can achieve the goal of limits by monitoring ourselves.
Fortunately, we saw several notifications in the UITextView instruction document:
NSString * const UITextViewTextDidBeginEditingNotification;NSString * const UITextViewTextDidChangeNotification;NSString * const UITextViewTextDidEndEditingNotification;
You can also learn about any of the notifications.UITextView
The input text has changed. We can do this with the entire helper class. The code will not be pasted out. You can also test it yourself and want to see the complete code here.