shouldChangeCharactersInRange调用两次

有时候,当我只打一个字符的时候,shouldChangeCharactersInRange被调用两次。

例如,我input'avion par c',程序被调用并添加第二个'c'结果'avion par cc' – 我怎样才能避免这种情况?

这发生只是因为我将应用程序迁移到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; } 

这个例程在字符被添加到string之前调用,只是为了检查字符是否被允许

您正在手动将字符添加到文本字段。 这是没有必要的,你得到的function委托。 你唯一要做的就是返回YES或NO。