欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UITextField输入长度限制

程序员文章站 2022-03-02 12:09:30
...

方法一:
添加UIControlEventEditingChanged事件处理

  • 添加事件
[self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  • 实现- textFieldDidChange:方法
#define kLimitLenth 11
- (void)textFieldDidChange:(UITextField *)textField
{
    UITextRange *selectedRange = textField.markedTextRange;
    if (!selectedRange || selectedRange.empty) {
        //这里取到textfielf.text最后的值 进行检索
        //NSLog(@"selectedRange textField.text [%@]", textField.text);
        NSString *text = textField.text;
        NSUInteger len = kLimitLenth;
        if (text.length >= len) {
            textField.text = [text substringToIndex:len];
            text = textField.text;
        }    
    }
}

方法二:
设置委托 - textField: shouldChangeCharactersInRange:replacementString来处理

#define kLimitLenth 11
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (range.length >= 1) {
       return YES;
    }
    
    UITextRange *selectedRange = textField.markedTextRange;
    if (!selectedRange || selectedRange.empty) {
        NSString *text = textField.text;
        NSMutableString *mString = [NSMutableString stringWithString:text];
        [mString insertString:string atIndex:range.location];
        NSUInteger len = kLimitLenth;
        if (mString.length >= len) {
            textField.text = [mString substringToIndex:len];
            return NO;
        }
    }
    
    return YES;
}