2013-04-23 109 views
1

最大字符長度目前我使用這種方法的UITextField - 通過表情符號在

(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    NSUInteger newLength = [textField.text length] + [string length] - range.length; 
    if(newLength <= 25) { 
     self.charsLeft.text = [NSString stringWithFormat:@"%d", 25 - newLength]; 
    } 
    return (newLength > 25) ? NO : YES; 
} 

其中charsLeft是標籤顯示在用戶界面。

問題出來了emoji。如果用戶輸入emoji符號,然後刪除它,newLength將等於1.因此,用戶將看到他只剩下24個字符。

我確實知道,表情符號是代理對的,但我不明白爲什麼如果你在

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

刪除比range.length將等於1,而不是2

我怎麼能修復用戶界面中的錯誤號碼? 我錯過了什麼?

回答

0

我也遇到了這個問題,我發現以下兩種解決方案來解決這個問題 嘗試

- (void)textViewDidChange:(UITextView *)textView 
{ 
    numberWordLabel.text = [NSString stringWithFormat:@"%d/25",textView.text.length]; 
} 

使用NSNotificationCenter(從Does Key Value Observing Work on UITextView's Text Property?

- (id)init 
{ 
    [super init]; 
    if (self) 
    { 
     NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
     [nc addObserver:self 
       selector:@selector(textDidChange:) 
        name:UITextViewTextDidChangeNotification 
       object:nil]; 
    } 
    return self; 
} 

- (void)dealloc 
{ 
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
    [nc removeObserver:self]; 
} 

- (void)textDidChange:(NSNotification *)note 
{ 
    NSLog(@"Observation..."); 
} 
+0

謝謝。第二個解決方案就是我一直在尋找的。 'UITextFieldDelegate'沒有'didChange'方法,所以第一次修復不適合我。我仍然認爲這個問題是SDK中的bug) – thoughtf00l 2013-05-21 14:16:28