The length of UITextField is limited.

Source: Internet
Author: User
Tags uicontrol

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.UITextFieldDelegateTo 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.UITextFieldDefine an attribute in. Let's study it.UITextFieldSee if it is possible.

@interface UITextField : UIControl...

  UITextFieldIs inherited fromUIControlSo 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

InUITextFieldWe 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. ThatUITextViewCan we do the same?

@interface UITextView : UIScrollView

Unfortunately, as shown above,UITextViewYesUIScrollViewNotUITextFieldThat isUIControlThat isUITextViewNot likeUITextFieldIn 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.UITextViewThe 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.
  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.