2011-04-03 101 views
3

我有一個文本字段,我想限制可以輸入到160個字符的文本。此外,我需要一個計數器來獲取當前文本的長度。如何限制文本輸入和字符數?

我解決它使用的NSTimer

[NSTimer scheduledTimerWithTimeInterval:0.5 target:self 
     selector:@selector(countText) 
     userInfo:nil 
     repeats:YES]; 

我顯示的長度是這樣的:

-(void)countText{ 
    countLabel.text = [NSString stringWithFormat:@"%i", 
           _textEditor.text.length]; 
} 

這是不是最好的櫃檯的解決方案,因爲它依賴於時間,而不是在keyUp事件上。有沒有辦法捕捉這樣的事件並觸發一種方法?

還有一件事,是否可以阻止/限制文本輸入,例如:通過在文本字段上提供最大長度參數?

回答

10

這是(或應是)委託方法的正確版本:

- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { 
// "Length of existing text" - "Length of replaced text" + "Length of replacement text" 
    NSInteger newTextLength = [aTextView.text length] - range.length + [text length]; 

    if (newTextLength > 160) { 
     // don't allow change 
     return NO; 
    } 
    countLabel.text = [NSString stringWithFormat:@"%i", newTextLength]; 
    return YES; 
} 
+1

這對於類似英語的非傳輸)的語言,但對於某些需要拼寫轉移的語言(例如日語或中文),有時計數不正確。例如,當您在拼寫時嘗試在日語鍵盤上點擊「に」時,它會計爲2,儘管正常情況下它會計爲1.另外,當您在拼寫時點擊刪除按鈕時,計數數字剛剛搞砸了...... – inexcii 2014-05-15 07:07:04

+0

絕佳答案...很多 – 2015-06-08 12:05:21

+0

@RalphZhouYuan是正確的。 ' - [UITextField addTarget:forEvent:]'就夠用了。 – 2016-04-15 13:51:11

1

可以使用委託方法

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ 

if(textField.length < max){ 
    return NO; 
}else return YES; 

}

,並設置最大長度,返回NO。

+0

textFieldShouldBeginEditing:只會阻止開始輸入或不輸入。每次用戶輸入密鑰時都必須進行閾值檢查。 – nacho4d 2011-04-03 11:07:56

3

實現一些UITextFieldDelegate協議方法

_textEditor.delegate = self; 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 
    int len = [textField.text length]; 
    if(len + string.length > max ||){ return NO;} 
    else{countLabel.text = [NSString stringWithFormat:@"%i", len]; 

返回YES;} }

+0

這允許在文本中有161個字符。禁用刪除,一旦161那裏。它允許粘貼超過160個字符的文本。問題不是那麼簡單。 – 2011-04-03 11:07:43

+0

我覺得現在是固定的。 ;) – nacho4d 2011-04-03 11:12:01

+0

是的,第一個問題是固定的。但是你不能在150個字符的選擇上粘貼20個字符;-) – 2011-04-03 11:17:21

1

使用以下代碼限制UITextField中的字符,以下代碼在UITextField中接受25個字符。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
     { 
      NSUInteger newLength = [textField.text length] + [string length] - range.length; 
      return (newLength > 25) ? NO : YES; 
     }