Word limit for Uitextfield in iOS

Source: Internet
Author: User

At first, the use of shouldChangeCharactersInRange

Http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield


This is possible in cases where the input is all in English. However, when the input is in Chinese, because Shouldchangecharactersinrange determines the current keyboard character number, there will be a problem: for example, you have 2 words left to play, you want to enter "Zhang San", "Zhang" Pinyin is Zhang, You cannot enter the zh when you enter it. Obviously, such results are not what we want.

Also, shouldChangeCharactersInRange there is no response to the final pinyin to the kanji process.

And then we found a solution that was basically possible:

http://blog.sina.com.cn/s/blog_60f977e70101g4gj.html#cmt_3529521

Register <UITextFieldTextDidChangeNotification> notice in Viewdidload.

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:)           name:@"UITextFieldTextDidChangeNotification" object:myTextField];

Then implement the Listening method:

-(void) textfieldeditchanged: (nsnotification *) obj{Uitextfield *textfield = (Uitextfield *) Obj.object; NSString *tobestring = Textfield.text; NSString *lang = [[Uitextinputmode currentinputmode] primarylanguage]; Keyboard input mode if ([Lang isequaltostring:@ "Zh-hans"]) {//Simplified Chinese input, including simplified pinyin, fitness wubi, simplified handwriting uitextrange *selectedrange = [TextField Markedtextrange]; Get the highlighted part uitextposition *position = [TextFieldpositionFromPosition:selectedRange.start offset:0]; If there is no highlighted word, the word count and limit if (!position) {if (Tobestring.length > Kmaxlength Textfield.text = [tobestring substringtoindex:kmaxlength]; }}//There is a highlighted string, then the text is not counted and restricted else{}}//Chinese input method directly to its statistical restrictions, regardless of other languages else{if (Tobestring.length > Kmaxlength) {textfield.text = [tobestring substringtoindex:kmaxlengt h]; } }}

Everything seems to be good. The object is achieved by intercepting the characters. Then the tutor told me that I had to hang up when I met emoji. Assume that the limit is entered in 15 characters, and the 15th character if the input is emoji, the emoji does not display properly. Because emoji is a two-character size.

So, here's the idea of preventing this rough truncation method.

http://stackoverflow.com/questions/15775294/ Truncate-string-containing-emoji-or-unicode-characters-at-word-or-character-boun

Used rangeOfComposedCharacterSequencesForRange to prevent the whole word from being truncated within range.
However, iOS does not seem to recognize Chinese correctly composed character sequences , as long as two characters are recognized composed character sequences . It happens that the input emoji is currentInputMode not zh-Hans . Therefore, when the current input mode is Chinese, you can continue to use it substringToIndex for truncation. In the case of non-Chinese mode, be judged.
The code is as follows:

#pragma mark-notification method-(void) textfieldeditchanged: (nsnotification *) obj{Uitextfield *textfield = (UITextFi    ELD *) Obj.object;    NSString *tobestring = Textfield.text;    NSString *lang = [Textfield.textinputmode primarylanguage]; if ([lang isequaltostring:@ "Zh-hans"])//Simplified Chinese input {//Get highlighted part uitextrange *selectedrange = [TextField marked        TextRange];        Uitextposition *position = [TextField positionFromPosition:selectedRange.start offset:0];            No highlighted word, word count and limit if (!position) {if (Tobestring.length > Max_starwords_length) for typed text            {Textfield.text = [tobestring substringtoindex:max_starwords_length];        }}///Chinese Input method directly to its statistical restrictions, regardless of other language situation else {if (Tobestring.length > Max_starwords_length)            {Nsrange Rangeindex = [tobestring rangeofcomposedcharactersequenceatindex:max_starwords_length];           if (rangeindex.length = = 1) {Textfield.text = [tobestring substringtoindex:max_starwords_length]; } else {Nsrange rangerange = [tobestring rangeofcomposedcharactersequencesforrange:n                Smakerange (0, max_starwords_length)];            Textfield.text = [tobestring substringwithrange:rangerange]; }        }    }}

Looked at, QQ, know the change nickname.
is the English character to calculate a length, Chinese count two length, emoji count four length total length is 32. Forces the current keyboard input to be in English when you enter a text character that exceeds the specified length. If the remaining number of characters is less than or equal to 3, you cannot enter emoji.
QQ is also the English characters and Chinese separate calculation length, but when only one length left, the keyboard can not enter the full Hanyu Pinyin. This is the example of < Zhang San > mentioned above.
But it doesn't matter how long it is to change the nickname. If there are some places to write comments, there is still room for experience optimization.
Know two goods incredibly no length limit, but modified nickname actually to audit ...

October 14 Update
Later found that the third-party input method (such as Sogou, Baidu Input method) will appear errors, found only need to do so.

  Uitextfield *textfield = (Uitextfield *) Obj.object;    NSString *tobestring = Textfield.text;    Get the highlighted part uitextrange *selectedrange = [TextField markedtextrange];    Uitextposition *position = [TextField positionFromPosition:selectedRange.start offset:0];            If there is no highlighted word, the word count and limit if (!position) {if (Tobestring.length > Max_starwords_length            Nsrange Rangeindex = [tobestring rangeofcomposedcharactersequenceatindex:max_starwords_length]; if (rangeindex.length = = 1) {textfield.text = [tobestring substringtoindex:max_starwords_length            ]; } else {Nsrange rangerange = [tobestring rangeofcomposedcharactersequencesforrange:n                Smakerange (0, max_starwords_length)];            Textfield.text = [tobestring substringwithrange:rangerange]; }        }    }

UPDATE2: Monitoring changes can be directly[self addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
IOS9 shouldChangeCharactersInRange function has a bug, in Chinese input, the recommended word is not called shouldChangeCharactersInRange . So don't use it to judge the length of the text.

Word limit for Uitextfield in iOS

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.