美文网首页
UITextField输入长度限制

UITextField输入长度限制

作者: WeeverLu | 来源:发表于2016-06-03 17:21 被阅读90次

    方法一:
    添加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;
    }
    

    相关文章

      网友评论

          本文标题:UITextField输入长度限制

          本文链接:https://www.haomeiwen.com/subject/qbfldttx.html