我想逐个字符地比较字符串和用户输入。例如我想让用户输入“我有一个苹果”。并将输入与此字符串进行比较,以查看他的输入是否正确。当他输入错误的字符时,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;
}
答案 0 :(得分:2)
试试这个
- (void)textViewDidChange:(UITextView *)textView{ if(![myStringToCompareWith hasPrefix:textView.text]){ //call vibrate here } }
答案 1 :(得分: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;
}