shouldChangeCharactersInRange调用两次

时间:2013-12-03 14:01:16

标签: ios methods ios7 uitextfield xcode5

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

作为一个例子,我输入'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;
}

1 个答案:

答案 0 :(得分:0)

在将字符添加到字符串之前调用此例程,只是为了检查是否允许字符等。

您正在手动将字符添加到文本字段中。这不是必需的,您可以获得委派的功能。您在代码中唯一需要做的就是返回YES或NO。