2012-04-24 25 views
0

我遇到問題我正在跟蹤由用戶輸入的字符及其正常工作,但隨着用戶刪除文本字段和文本字段中的整個消息變爲空,其提供文本字段文本長度= 1。 它應該是0,我沒有得到它。任何幫助刪除字符串後的uitextfield文本長度

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

    if (textField == textfield1) 
    { 


     NSLog(@"%d",textfield1.text.length); 
     NSInteger charleft = (100 - textfield1.text.length); 
     NSLog(@"The Characters left are %d",charleft); 
     while(!(charleft<0)) 
     { 

      NSString *Charlength= [NSString stringWithFormat:@"%d",charleft];  
      Charcount.text= [ Charlength stringByAppendingFormat:@" Characters left"]; 
      return YES; 

     } 


     return NO; 

    } 

回答

-1

您可能在完整的猜測中看到\ b字符。

0

你計算你charleft處理當前的擊鍵,所以在Charlength.text值將會從之前,處理當前的按鍵值。如果您想Charlength顯示其餘字符,則需要在處理擊鍵後對其進行更新。

還有另一個副作用,你應該知道這裏:你不區分backspace和普通字符插入。一旦你超過了100個字符的閾值(因爲我描述的錯誤,現在真的是101),你永遠不會處理另一個字符,包括退格/刪除。這意味着一旦你的用戶超過了門檻,他們將被卡住,因爲他們將無法刪除一個字符。 (嘗試一下)。

+0

是的,你是對的,我只是嘗試過,它會發生什麼?可能的解決方案是什麼? – 2012-04-24 21:00:16

1
int maxChars = 100; 
    int charsLeft = maxChars - [textField.text length]; 

    if(charsLeft == 0) { 
     UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"No more characters" 
                 message:[NSString stringWithFormat:@"You have reached the character limit of %d.",maxChars] 
                 delegate:nil 
               cancelButtonTitle:@"Ok" 
               otherButtonTitles:nil]; 
     [alert show]; 
     [alert release]; 
    } 
    NSString *chrstr = [NSString stringWithFormat:@"%d characters remaining.",charsLeft]; 
    Charcount.text=chrstr;// 
NSLog(@"%@",chrstr; 
}, 

它已經解決了我的問題我使用editind更改選項將此uitextfield與此操作連接起來。