2016-01-13 19 views
0

我有3個文本字段,並且使用UITextFeildDelegate方法將每個文本字段的字符限制限制爲50,並且工作正常。現在,當我嘗試通過語音輸入文本而不是通過鍵盤輸入文本時,文本字段似乎接受超過50個字符,並且在語音輸入完成時,一段時間內整個文本消失。如何在通過語音輸入文本時限制文本字段中的文本

這裏是我的委託方法shouldChangeCharactersInRange

if(textField==self.optionATextField || textField==self.optionBTextField ||textField==self.optionCTextField) { 
    if(range.length + range.location > textField.text.length) { 
     return NO; 
    } 
    NSUInteger newLength = [textField.text length] + [string length] - range.length; 
    return newLength <= 50; 
} 

有沒有辦法做到這一點?我是否需要實施任何其他語音輸入方法才能正常工作?

希望你明白這個問題。 在此先感謝

+0

你想要的文本字段如果輸入的文本長度超過50個,會被截斷爲50個字符?順便說一句 - 你有同樣的需要,如果用戶粘貼文本以及使用語音? – rmaddy

+0

@rmaddy我想在50個字符到達時限制文本輸入...不截斷,既粘貼也不發言 – George

+0

可以說有40個字符,用戶粘貼20個字符。你想忽略整個20還是讓第一個10做到50? – rmaddy

回答

0

假設您想要輸入的文本被截斷爲最多50個字符,無論輸入方式,你可以做這樣的事情:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    if(textField==self.optionATextField || textField==self.optionBTextField ||textField==self.optionCTextField) { 
     NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
     if (newText.length < 50) { 
      // Text length is still OK, let it through 
      return YES; 
     } else { 
      // The new text is too long - truncate and set the shorter value 
      newText = [newText substringToIndex:50]; 
      textField.text = newText; 

      return NO; 
     } 
    } else { 
     return YES; // do whatever you need here 
    } 
} 
+0

我嘗試了代碼...但它似乎接受超過50個字符,而通過語音輸入。 – George

+0

通過語音輸入時是否調用'shouldChangeCharactersInRange'?設置一箇中斷點,看看會發生什麼。 – rmaddy

+0

'shouldChangeCharactersInRange'僅在完成按鈕被單擊時調用,而不是在通過語音輸入文本時調用。 – George

相關問題