Restrictions on the number of input words have been done before, there are many ways online.
But they are not perfect, the former testers did not try their best to fault, so fooled past.
Now the tester of this project is really fair bet to find Bugs ....
1. The general method is through the Uitextfield proxy method
#pragmamark-uitextfielddelegate-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) Range Replacementstring: (NSString *)string{ if(TextField = =self.textfieldname) {if(string. length = =0)returnYES; Nsinteger Existedlength=textField.text.length; Nsinteger Selectedlength=range.length; Nsinteger Replacelength=string. Length; if(Existedlength-selectedlength + replacelength > -) { returnNO; } } returnYES;}
But this method still has a bug ... This method is easy to be in Chinese Association, paste and other ways to break the limit length.
2. Add an event to Uitextfield and intercept it to the maximum length in the event
[Self.textfieldname addtarget:self Action: @selector (Textfielddidchange:) forControlEvents: Uicontroleventeditingchanged]; -(void) Textfielddidchange: (Uitextfield *) textfield{ if (TextField = = Self.textfieldname) {if ) {= [textfield.text substringtoindex:15 ]; } }}
Do you think this is done with the Chinese Association, paste the bug, you have peace of mind ... This method still has a bug, if the input to the left one character, then input emoji? Emoji occupies 2 characters and is truncated to half a emoji, and a string containing half a emoji becomes nil when the URL is encoded.
3. Limit the number of words to enter the perfect solution
In fact, it was adjusted on program 2.
-(void) Textfielddidchange: (Uitextfield *) textfield{ if (TextField = = Self.textfieldname ){if) { //emoji is 2 characters, if it is more than half a emoji , use a 15-bit position to intercept a range nsrange range = [ emoji a sequence of characters]with emoji truncated to 2 half // exceeding the maximum length. Textfield.text rangeofcomposedcharactersequenceatindex:[]; = [Textfield.text substringToIndex:range.location]; }}
IOS Limit input words perfect solution