问题
Sometimes, shouldChangeCharactersInRange is called twice when I hit only one character.
As an exemple, i enter 'avion par c', the procedure is called and add me a second 'c' result is 'avion par cc' - How can I avoid that ?
This happened only since I migrate the application to iOS 7, xCode 5.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
wordSearching = YES;
if ([string isEqualToString:@"\n"]) {
[self textFieldDoneEditing];
return NO;
}
if ([string isFirstCharacterPunctuation]) {
NSLog(@"punctuation detected");
[self replaceWordEditedByFirstSuggestion];
[self hideSuggestions];
return YES;
}
NSLog(@"Search : %@", string);
//NSLog(@"textField : %@", textField);
NSLog(@"self : %@", self.textEdited);
string = [string lowercaseString];
self.textEdited = [[NSString stringWithString:textField.text] lowercaseString];
self.textEdited = [textEdited stringByReplacingCharactersInRange:range withString:string];
indexEdition = MIN(range.location + 1, [textEdited length]);
self.wordEdited = [textEdited wordAtIndex:indexEdition];
NSLog(@"editing at [%d '%@' '%@' '%@']", indexEdition, wordEdited, string, textEdited);
if ([self canBeDirectAccess:textField.text]) {
//[self hideSuggestions];
NSLog(@"Direct Access");
return YES;
}
[self updateSuggestionsFor:wordEdited];
return YES;
}
回答1:
This routine is called before the characters are added to the string, just to check if the characters are allowed etc.
You are manually adding the characters to the textfield. That is not necessary, you get that functionality delegated. The only thing you have to do in you code is to return YES or NO.
来源:https://stackoverflow.com/questions/20353191/shouldchangecharactersinrange-call-twice