Uitextview Word limit

Source: Internet
Author: User

Original address: Detailed explanation (common uitextview input word limit) one---Fixed length

Limit the number of words uitextview input, commonly used Uitextview delegate:

-(BOOL) TextView: (Uitextview *) TextView Shouldchangetextinrange: (nsrange) range   *) text; // there is a touch on the input, but it does not trigger    for the Chinese keyboard to show the legend selection -(void) Textviewdidchange: (Uitextview *) TextView; // triggered when the input and the above code returns YES. or triggered when you select a legend on the keyboard. 

The first is for restricting input and the second is for dynamic calculation of the remaining word count.

#define Max_limit_nums     // to limit maximum input of 100 characters only

Full code:

-(BOOL) TextView: (Uitextview *) TextView Shouldchangetextinrange: (nsrange) Range Replacementtext: (NSString*) Text {uitextrange*selectedrange =[TextView Markedtextrange]; //get highlighted partsUitextposition *pos = [TextView positionFromPosition:selectedRange.start offset:0]; //get highlighted parts of the content//NSString * SelectedText = [TextView textinrange:selectedrange]; //allow input If there is a highlight and the current word start position is less than the maximum limit    if(Selectedrange &&POS) {Nsinteger Startoffset=[TextView offsetFromPosition:textView.beginningOfDocument ToPosition:selectedRange.start]; Nsinteger Endoffset=[TextView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end]; Nsrange Offsetrange= Nsmakerange (Startoffset, Endoffset-startoffset); if(Offsetrange.location <max_limit_nums) {              returnYES; }          Else          {              returnNO; }} nsstring*comcatstr =[Textview.text Stringbyreplacingcharactersinrange:range Withstring:text]; Nsinteger Caninputlen= Max_limit_nums-comcatstr.length; if(Caninputlen >=0)      {          returnYES; }      Else{Nsinteger len= Text.length +Caninputlen; //prevents error when Text.length + Caninputlen < 0 o'clock, making rg.length an illegal maximum positive numberNsrange RG = {0, MAX (Len,0)}; if(Rg.length >0) {NSString*s =@""; //determine if only normal characters or ASC codes (for Chinese and Emoticons return no)BOOL ASC =[text canbeconvertedtoencoding:nsasciistringencoding]; if(ASC) {s= [text Substringwithrange:rg];//because it's ASCII, it's not wrong to take it directly.            }              Else{__block Nsinteger idx=0; __block NSString*trimstring =@"";//the truncated string//using string traversal, this method can know exactly whether each emoji is a Unicode or two[Text Enumeratesubstringsinrange:nsmakerange (0, [text length]) options:nsstringenumerationbycomposedcharactersequence S Usingblock:^ (nsstring* substring, nsrange substringrange, Nsrange Enclosingrange, bool*stop) {                                                                                                  if(IDX >=rg.length) {*stop = YES;//remove the need to break, improve efficiency                                                   return ; } trimstring=[trimstring stringbyappendingstring:substring]; IDX++;                                    }]; S=trimstring; }              //rang refers to the substitution process from the current cursor (note that if yes is returned after this sentence is executed, the Didchange event is triggered)[TextView settext:[textview.text stringbyreplacingcharactersinrange:range withstring:s]; //since it is out of the partial interception, which must be the maximum limit. Self.lbNums.text = [NSString stringWithFormat:@"%d/%ld",0,(Long) Max_limit_nums]; }          returnNO; }    }    - (void) Textviewdidchange: (Uitextview *) TextView {uitextrange*selectedrange =[TextView Markedtextrange]; //get highlighted partsUitextposition *pos = [TextView positionFromPosition:selectedRange.start offset:0]; //If the highlight is changing in the change, don't count the characters.    if(Selectedrange &&POS) {          return; } nsstring*nstextcontent =Textview.text; Nsinteger Existtextnum=nstextcontent.length; if(Existtextnum >max_limit_nums) {          //The character that is intercepted to the maximum position (because the outside section is processed at should, which is where the efficiency is no longer judged)NSString *s =[Nstextcontent substringtoindex:max_limit_nums];      [TextView settext:s]; }            //do not let display negative mouth daySelf.lbNums.text = [NSString stringWithFormat:@"%ld/%d", MAX (0, Max_limit_nums-existtextnum), max_limit_nums]; }  

Places to be aware of:

1. In, English characters are limited when entering.

2. Take emoji when the interception shows half or garbled character processing.

Modification of the above code for emoji length:

[Text Enumeratesubstringsinrange:nsmakerange (0, [text length]) options:nsstringenumerationbycomposedcharactersequences Usingblock:^ (nsstring* substring, nsrange substringrange, Nsrange Enclosingrange, bool*stop) {Nsinteger Steplen=substring.length; if(IDX >=rg.length) {*stop = YES;//remove the need to break, improve efficiency                                   return ; } trimstring=[trimstring stringbyappendingstring:substring]; IDX= idx + Steplen;//This changes, using the length of the string as the step}];

Treat a emoji of length 2 as 1 characters:

[Text Enumeratesubstringsinrange:nsmakerange (0, [text length])                                                options: Nsstringenumerationbycomposedcharactersequences                                             

//////////////////////////////////////////

The article is very useful for the discussion of all kinds of text content.

Uitextview Word limit

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.