iOS UITextField 字数限制

用UItextField的代理方法来限制字数或即时判断输入内容有效性等问题的时候是不能完美满足需求的,这篇文章介绍另一种方法可能对你有很大启发。因为UItextField和UIbutton一样是继承于UIControl的,所以是可以addTarget的,如下:

[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

然后实现textFieldDidChange:的方法,这个方法在输入或删除每个字符的时候都会调用。

- (void)textFieldDidChange:(UITextField *)textField {
    
    NSString *toBeString = [textField.text lowercaseString];
    textField.text = toBeString;
    //限制字数
    _limitNum = 16;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
    if (!position||!selectedRange)
    {
        if (toBeString.length > _limitNum)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:_limitNum];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:_limitNum];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, _limitNum)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
    
    //commitButton 是否可以点击
    if (_newPasswordTextField.text.length>5&&_confirmPasswordTextField.text.length>5&&_newPasswordTextField.text.length==_confirmPasswordTextField.text.length) {
        _commitButton.backgroundColor = SAColorByRGB(0, 124, 246);
        _commitButton.userInteractionEnabled = YES;
    }else{
        _commitButton.backgroundColor = SAColorByRGB(219, 219, 219);
        _commitButton.userInteractionEnabled = NO;
    }
    
    //实时查看密码格式是否正确
    if (textField == _newPasswordTextField) {
        if (_newPasswordTextField.text.length>5) {
            if ([self isNumberWithLetterType:_newPasswordTextField.text]) {
                _newPasswordTextField.type = SAFloatLabeledTextFieldTypeNormal;
            }else{
                _newPasswordTextField.type = SAFloatLabeledTextFieldTypeWrong;
            }
        }else{
            _newPasswordTextField.type = SAFloatLabeledTextFieldTypeNormal;
        }
        
    }

}
/** 判断是否是数字+字母 16位*/
- (BOOL)isNumberWithLetterType:(NSString *)string {
    NSString *regex = @"(?=.*\\d)(?=.*[a-zA-Z]).{1,16}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:string];
}

你可能感兴趣的:(iOS UITextField 字数限制)