To limit the number of input words for a Uitextfield (reference link), the first thought should be
Uitextfielddelegate
Proxy methods to limit:
-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) string; return NO to the change text
For example, to set the word limit to 20:
-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) string{ return NO; return YES;}
But such restrictions are simple and rude, may affect the user's normal logic input, such as 20 characters entered, to backspace back the delete character.
At this time we may consider "Detect backspace in Uitextfield", such as simply to determine whether the length of the replacementstring is 0.
Then we may also encounter the user has entered 20 characters, this time continue to enter--- Just select some text to replace the -----can not be done, which also prevents the user's normal operation, Therefore, the code version of the restriction may evolve to the following:
#pragma mark-uitextfielddelegate-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) Range replacementstring: (NSString *) string{if (String.Length = = 0) return YES; Nsinteger existedlength = textField.text.length; Nsinteger selectedlength = range.length; Nsinteger replacelength = string.length; if (Existedlength-selectedlength + Replacelength >) {return N O }} return YES;}
You may feel basically done here, but when you enter 19 characters, the 20th character continues to be entered as a Chinese character, then the system will provide a series of subsequent words on the keyboard, and you will find that this way you can enter the word consecutively to break the 20-character limit. WTF
When we get here, we might want to have a similar
-(void) Textfielddidchange: (Uitextfield *) TextField
callback method, but unfortunately not.
Of course, we can also pass
-(void) textfielddidendediting: (Uitextfield *) TextField;
The callback method truncates the text at the end of the edit, although it is somewhat abrupt in the user experience.
But when we go in and look for the callback method in the UITextField.h header file, we may find that there is a message notification name at the bottom:
Uikit_extern NSString *const uitextfieldtextdidchangenotification;
However, listen to the message also remember to release the listening, usually I also used to listen to the message of the code unified in a method, looks a bit "a".
Fortunately, the Uitextfield itself provides the appropriate event monitoring:
[TextField addtarget:self Action: @selector (Textfielddidchange:) forcontrolevents:uicontroleventeditingchanged];
This allows you to better limit the input length:
-(void) Textfielddidchange: (Uitextfield *) textfield{ if (TextField.text.length >) { textfield.text = [Textfield.text substringtoindex:20]; }}
How to better limit the input length of a Uitextfield