0

我想将字符串与用户输入的字符逐个字符进行比较。例如,我想让用户输入“我有一个苹果”。并将输入与此字符串进行比较,以查看他的输入是否正确。当他输入错误的字符时,iphone会立即振动通知他。问题是我发现一些像空格这样的字符会调用委托方法两次

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

当我按空格键时,我第一次将文本与 ' ' 进行比较时,结果会告诉我它们是同一个字符。但在那之后,我必须将字符串字符的索引推进到下一个。而第二次调用委托方法,iphone会震动。关于如何解决这个问题的任何想法?

这是我的代码:


strText = @"I have an apple.";
index = 0;

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSRange rg = {index, 1};
    NSString *correctChar = [strText substringWithRange:rg];
    if([text isEqualToString:correctChar])
    {
        index++;

        if(index == [strText length])
        {
            // inform the user that all of his input is correct
        }
        else
        {
            // tell the user that he has index(the number of correct characters) characters correct
        }
    }
    else {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        return NO;
    }

    return YES;
}

4

2 回答 2

2

试试这个

- (void)textViewDidChange:(UITextView *)textView{
   if(![myStringToCompareWith hasPrefix:textView.text]){
    //call vibrate here
   }
}
于 2009-11-12T09:20:40.790 回答
0

基于 Morion 关于使用 hasPrefix: 的建议,我认为这是您正在寻找的解决方案:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    // create final version of textView after the current text has been inserted
    NSMutableString *updatedText = [NSMutableString stringWithString:textView.text];
    [updatedText insertString:text atIndex:range.location];

    if(![strTxt hasPrefix:updatedText]){
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        return NO;
    }

    return YES;
}
于 2009-11-12T09:43:48.663 回答