我想比較一個字符串與用戶輸入字符。例如我想讓用戶輸入「我有一個蘋果」。並將輸入與此字符串進行比較以查看他的輸入是否正確。當他輸入錯誤的字符時,iphone會立即振動以通知他。問題是,我發現像空間這樣的字符會調用委託方法兩次UITextView中的用戶輸入調用委託方法兩次?
- (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;
}
謝謝。我通過用你的代碼替換我的else塊並且在振動之後解決了我的問題,我刪除了用戶輸入的錯誤字符。 – 2009-11-12 09:38:33
我只是想了解問題的原因。你知道爲什麼空格鍵只是爲委託方法生成地址而不是空白字符的原因嗎?爲什麼shouldChangeTextInRange方法被調用兩次? – 2009-11-13 05:11:35