The limitations of the maximum number of characters and bytes in IOS Uitextfield _ios

Source: Internet
Author: User
Tags strlen truncated

Objective

Here I give you a few groups of test cases can be a try, why not easy to use.

1, limit 10 bytes, enter 2 emoj after 8 bytes (a emoj is 4 bytes), then enter a Chinese to see how the results (Chinese UTF8 accounted for 3 bytes)

2, limit 5 characters, one emoj is 2 characters, the other is one. Enter two emoj at this time, then enter Chinese, then Chinese Lenovo try.

As far as the current situation is concerned, there is not a common package that can limit the number of characters and bytes by looking at a lot of data. Here is a comprehensive summary, and the encapsulation. Welcome everyone to download.

A. Character limit

1. Error method

The common method is wrong, causing the emoj expression to intercept the problem

-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) string
{
 if (range.length + range.location > TextField.text.length)
 {return
 NO;
 }
 
 Nsuinteger newlength = [Textfield.text length] + [string length]-range.length;
 return newlength <= 5;
}

This restriction method can cause this condition to appear under pinyin and cannot be entered. Cannot enter full 5 characters. There's a problem with Emoj's face.

2. Recommended methods

Use Rangeofcomposedcharactersequencesforrange to prevent whole words from being truncated within range

-(void) Textfielddidchange: (Uitextfield *) TextField
{
 nsstring *tobestring = textfield.text;

 Uitextrange *selectedrange = [TextField markedtextrange];
 Uitextposition *position = [TextField positionFromPosition:selectedRange.start offset:0];
 
 Without the highlighted word, the words are counted and restricted to prevent Chinese being truncated
 if (!position) {
 if (Tobestring.length > _maxlength) {
  // There are problems in Chinese and emoj expressions, which need to be handled
  nsrange rangerange = [tobestring rangeofcomposedcharactersequencesforrange:nsmakerange (0, _maxlength)];
  Textfield.text = [tobestring substringwithrange:rangerange];
 }
 }

Two. Byte limit

1. Limit the number of bytes

In UTF8, the English and the number are 1 bytes, the man is 3 bytes, the emoji is 3 or 4 bytes. Here is more difficult than the above, if the interception failed, most likely garbled. Here we practice the following

-(void) Textfielddidchange: (Uitextfield *) TextField
{
 nsstring *tobestring = textfield.text;
 ---byte processing
 nsinteger bytescount = strlen ([Textfield.text utf8string]);
 if (Bytescount > _maxbyteslength) {
 NSString *content = [Textfield.text substrwithutf8len: (int) _maxbyteslength] ;
 Textfield.text = content;
 }

-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) string{
 
 nsstring * inputstring = [Textfield.text stringbyreplacingcharactersinrange:range: string];
 
 Limit bytes
 if ([inputstring length] > 0) {
 Nsinteger len = strlen ([inputstring utf8string]);
 if (Len > _maxbyteslength) {return
  NO;
 }
 else {return
  YES
 }
 }
 Return YES
}

This can not only be in the limit, in the textfielddidchange need to do the Chinese Association to do the processing.

Three. Give up the keyboard

1. When you can get the Uitextfield

-(BOOL) Textfieldshouldreturn: (Uitextfield *) TextField
{return
 [TextField resignfirstresponder];
}

2. Click View to disappear when using

[Self.view Endediting:yes];

3. When it is difficult to obtain

[[UIApplication sharedapplication] sendaction: @selector (Resignfirstresponder) To:nil From:nil];

Or

[[[[UIApplication sharedapplication] Keywindow] endediting:yes];

4.Tableview Click on the blank space or scroll away

{
 UITapGestureRecognizer *singletap = [[UITapGestureRecognizer alloc] initwithtarget:self action: @selector ( fingertapped:)];
 [Self.view Addgesturerecognizer:singletap];
}

#pragma mark-keyboard disappears
-(void) fingertapped: (UITapGestureRecognizer *) gesturerecognizer{
 [Self.view endediting: YES];
-(void) scrollviewwillbegindragging: (Uiscrollview *) scrollview{
 [Self.view endediting:yes];
}

Four. Regular expression restrictions

Refer to the Regular Expression syntax table, here I provide two expressions for you to refer to, an int, a no unsignedint

-(BOOL) Istextfieldmatchwithregularexpression: (NSString *) exporession{
 
 nspredicate *predicate = [NSPredicate predicatewithformat:@ "SELF matches%@", exporession];
 return [predicate evaluatewithobject:self];
}
-(BOOL) istextfieldintvalue{return
 [self istextfieldmatchwithregularexpression:@ [-]{0,1}[0-9]*];
}
-(BOOL) istextfieldunsignedintvalue{return
 [self istextfieldmatchwithregularexpression:@ [0-9]+];
}

Five. Uitextfield keyboard Event Multiple callback problem

1. Keyboard Height occlusion problem

In general, we use the following code to see if the current TextField is under the keyboard, calculate the distance between the top of the keyboard and the bottom of the TextField, and then do an offset animation

-(void) Keyboardwillshow: (nsnotification *) Notification {nsdictionary *userinfo = [notification UserInfo];
 nsvalue* avalue = [UserInfo Objectforkey:uikeyboardframeenduserinfokey];
 CGRect keyboardrect = [Avalue cgrectvalue];
 
 Keyboardrect = [Self.view convertrect:keyboardrect fromview:nil];
 
 CGFloat keyboardtop = KEYBOARDRECT.ORIGIN.Y;
 
 CGFloat offset = self.normalTextField.frame.size.height + self.normaltextfield.frame.origin.y-keyboardtop;
 Nsvalue *animationdurationvalue = [UserInfo Objectforkey:uikeyboardanimationdurationuserinfokey];
 Nstimeinterval animationduration;
 
 [Animationdurationvalue getvalue:&animationduration];
 if (Offset > 0) {//Animate the resize of the text view ' s frame in sync with the keyboard ' s appearance.
 [UIView Beginanimations:nil Context:null];

 [UIView setanimationduration:animationduration];
 CGRect rect = CGRectMake (0.0f,-offset,self.view.frame.size.width,self.view.frame.size.height);
 Self.view.frame = rect; [UIView CommitaniMations]; }
}

1. Real Machine

If the Chinese input method is used, the registered Keyboardwillshow will be recalled two times. The first time is the keyboard default height of 216, and the second is the height of the keyboard navigation bar.

2. Simulator

The first time you eject the keyboard is fine

Print UserInfo:

(LLDB) Po userInfo
{
 uikeyboardanimationcurveuserinfokey = 7;
 Uikeyboardanimationdurationuserinfokey = "0.25";
 Uikeyboardboundsuserinfokey = "Nsrect: {{0, 0}, {414, i}}";
 Uikeyboardcenterbeginuserinfokey = "Nspoint: {207, 849}";
 Uikeyboardcenterenduserinfokey = "Nspoint: {207, 623}";
 Uikeyboardframebeginuserinfokey = "Nsrect: {{0, 736}, {414, i}}";
 Uikeyboardframeenduserinfokey = "Nsrect: {{0, 510}, {414, i}}";
 Uikeyboardislocaluserinfokey = 1;
}

At this point we go to the small sphere next to 123 and the following figure appears:

Print UserInfo:

(LLDB) Po userInfo
{
 uikeyboardanimationcurveuserinfokey = 7;
 Uikeyboardanimationdurationuserinfokey = "0.25";
 Uikeyboardboundsuserinfokey = "Nsrect: {{0, 0}, {414, 271}}";
 Uikeyboardcenterbeginuserinfokey = "Nspoint: {207, 623}";
 Uikeyboardcenterenduserinfokey = "Nspoint: {207, 600.5}";
 Uikeyboardframebeginuserinfokey = "Nsrect: {{0, 510}, {414, i}}";
 Uikeyboardframeenduserinfokey = "Nsrect: {{0, 465}, {414, 271}}";
 Uikeyboardislocaluserinfokey = 1;
}

The keyboard is obscured.

Summary: Observe the result, found this rule, print time, there is another problem is that the Chinese keyboard will be recalled two times the first time.

Keyboardrect = [Self.view convertrect:keyboardrect fromview:nil];

So get rid of that sentence.

Six. Use the encapsulated Xxtextfield

Uitextview, if there is a keyboard in the Uitextfield, an automatic bouncing event is needed and the content offset after the bounce is processed to the parent view. It can be very complicated if each page is implemented once. Here we introduce an automated processing mechanism. Before that, let's introduce the word processing framework. Finally, I would like to recommend the Xxtextfield, you can also add some regular expressions on this basis.

1. Solve the problem of TextField occlusion in UIView

_textfieldname.keyboardtype = Uikeyboardtypedefault;
_textfieldname.inputtype = Xxtextfieldtypeonlyint;
_textfieldname.maxlength = 5;

_textfieldpwd.inputtype = Xxtextfieldtypeforbidemoj;

#import "XXKeyboardManager.h" @interface XXCORRECTVC () <XXKeyboardManagerShowHiddenNotificationDelegate> @end
 @implementation XXCORRECTVC-(void) viewdidload {[Super viewdidload];
 [[Xxkeyboardmanager sharedinstance] setdelegate:self];
Do no additional setup after loading the view from its nib. #pragma mark-keyboardshow/hidden-(void) Showkeyboardwithrect: (cgrect) keyboardrect withduration: (cgfloat) animationduration {cgfloat offset = self.textFieldCorrect.frame.size.height + SELF.TEXTFIELDCORRECT.FRAME.ORIGIN.Y-
 KEYBOARDRECT.ORIGIN.Y;
 if (Offset < 0) {return; } [UIView animatewithduration:animationduration delay:0.f options:uiviewanimationoptioncurveeaseinout Animat ions:^{CGRect rect = CGRectMake (0.0f,-OFFSET,SELF.VIEW.FRAME.SIZE.WIDTH,SELF.VIEW.FRAME.SIze.height);
 Self.view.frame = rect;
} completion:^ (BOOL finished) {}]; }-(void) Hiddenkeyboardwithrect: (cgrect) keyboardrect withduration: (cgfloat) animationduration {[UIView animateWith Duration:animationduration delay:0.f options:uiviewanimationoptioncurveeaseinout animations:^{Self.textFie
 Ldcorrect.frame = Self.view.bounds;
} completion:^ (BOOL finished) {}]; } @end

2. Troubleshoot the keyboard occlusion problem in UITableView

/
 * * When the keyboard is to be displayed/
/(void) Showkeyboardwithrect: (cgrect) Keyboardrect
    withduration: (cgfloat) animationduration{
 
 cgsize kbsize = keyboardrect.size;
 
 Uiedgeinsets contentinsets = uiedgeinsetsmake (0.0, 0.0, kbsize.height, 0.0);
 _basetableview.contentinset = contentinsets;
 _basetableview.scrollindicatorinsets = contentinsets;
 
 If Active Text field is hidden by keyboard, scroll it it's visible
 //Your app might not need or want this Beha Vior.
 CGRect arect = self.view.frame;
 ARect.size.height-= kbsize.height;
 
 if (! Cgrectcontainspoint (Arect, _activecell.frame.origin)) {
  [_basetableview scrollrecttovisible:_ Activecell.frame Animated:yes];
 }
 * * * When the keyboard is going to disappear/
-(void) Hiddenkeyboardwithrect: (cgrect) Keyboardrect
     withduration: (cgfloat) animationduration{
 _basetableview.contentinset = Uiedgeinsetszero;
 _basetableview.scrollindicatorinsets = Uiedgeinsetszero;
}

Summarize

The above is the full content of this article, I hope this article on the content of Android developers can help, if you have questions you can message exchange.

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.