一般,当我们需要限制textfield的输入字符限制时,调用- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string方法来实现,比如:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (self.rename == textField)  //判断是否时我们想要限定的那个输入框
    {
        NSString * toBeString = [self.rename.text stringByReplacingCharactersInRange:range withString:string];
        if (range.location >= 8)
        {
            return NO;
        }      
    return YES;
}
但是,这带来了一个问题,就是如果当我们输入中文拼音时,拼音的输入会因为剩余字符的限制导致不能输入,而且在iOS中,拼音输入还占据两个字符!(真要命@#¥%)这就会导致很尴尬的问题,尤其当限制的数量比较小时(比如上面例子中的8),可能输如五个拼音就不能继续输入了,有木有大神知道怎么解决这个问题的,我是新手,最好的能说的详细一点,或者提供解决思路也行。

解决方案 »

  1.   

    试试这里的方法:http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfieldThe best way would be to set up a notification on the text changing. In your -awakeFromNib of your view controller method you'll want:
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(limitTextField:) name:@"UITextFieldTextDidChangeNotification" object:myTextField];
    Then in the same class add:- (void)limitTextField:(NSNotification *)note {
        int limit = 20;
        if ([[myTextField stringValue] length] > limit) {
            [myTextField setStringValue:[[myTextField stringValue] substringToIndex:limit]];
        }
    }
    Then link up the outlet myTextField to your UITextField and it will not let you add any more characters after you hit the limit. Be sure to add this to your dealloc method:
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:myTextField];
      

  2.   


    int limit = 20;
    根据需要改字数限制试试...
      

  3.   


    int limit = 20;
    根据需要改字数限制试试...
    改过了,就是输到limit数量的拼音,字符串会自己断掉,抓狂
      

  4.   

    1.使用正则表达式,判断哪些需要一个字符,哪些用多个字符,相加后再比较下
    2.根据你限制的个数计算出字符所需的宽度(可以用label,高度固定,宽度无限的情况),再将输入的字符串计算出宽度,进行比较