2009-11-12 92 views
0

我想比較一個字符串與用戶輸入字符。例如我想讓用戶輸入「我有一個蘋果」。並將輸入與此字符串進行比較以查看他的輸入是否正確。當他輸入錯誤的字符時,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; 
} 

回答

2

試試這個

- (void)textViewDidChange:(UITextView *)textView{ 
    if(![myStringToCompareWith hasPrefix:textView.text]){ 
    //call vibrate here 
    } 
} 
+0

謝謝。我通過用你的代碼替換我的else塊並且在振動之後解決了我的問題,我刪除了用戶輸入的錯誤字符。 – 2009-11-12 09:38:33

+0

我只是想了解問題的原因。你知道爲什麼空格鍵只是爲委託方法生成地址而不是空白字符的原因嗎?爲什麼shouldChangeTextInRange方法被調用兩次? – 2009-11-13 05:11:35

0

大廈使用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; 
} 
+0

我測試了你的代碼,發現當我輸入空格鍵時,insertString方法會拋出異常。它看起來像空格鍵不會爲委託方法生成一個字符串,而是一個地址。 – 2009-11-13 05:09:07

+0

它適用於我,我用你的確切的字符串(與空格)。你確定它是失敗的insertString嗎? – gerry3 2009-11-13 06:20:12