UITextField限制输入文字的个数

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

代码如下:

static constNSInteger Max_Character_Num =4;

    - (IBAction)onTextFieldEditingChanged:(id)sender  
    {  
        NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];  
        if ([lang isEqualToString:@"zh-Hans"]) {  
            UITextRange *selectedRange = [self.tagNameTextField markedTextRange];  
            UITextPosition *position = [self.tagNameTextField positionFromPosition:selectedRange.start offset:0];  
            if (!position) {  
                if (self.tagNameTextField.text.length > Max_Character_Num) {  
                    self.tagNameTextField.text = [self.tagNameTextField.text substringFrom:0 to:Max_Character_Num];  
                }  
            }  
        }else{  
            if (self.tagNameTextField.text.length > Max_Character_Num) {  
                self.tagNameTextField.text = [self.tagNameTextField.text substringFrom:0 to:Max_Character_Num];  
            }  
        }  
    }  
来自:http://blog.csdn.net/wang_lichun/article/details/45251217