iOS开发--UITextField限制输入文字的个数

项目需要输入框的文字最多为4个,为了实现这个功能,在网上把资料翻遍了,没有一个能用的。后来不得不自己实现,折腾了好久,终于搞定了。小技巧分享给大家。如果不行,请吊打我。大笑

代码如下:

static const NSInteger 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];
        }
    }
}




你可能感兴趣的:(iOS开发--UITextField限制输入文字的个数)