UITextField和UITextView限制输入字数的方法

1、UITextField限制输入字数的方法

#define MaxCount 100

// 监听textField的输入
[self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

- (void)textFieldDidChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    // 获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
    if (!position) {
        if (toBeString.length > MaxCount) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MaxCount];
            if (rangeIndex.length == 1) {
                textField.text = [toBeString substringToIndex:MaxCount];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MaxCount)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

2、UITextView限制输入字数的方法

#define MaxCount 100

self.textView.delegate = self;

/// 用此代理方法限制字数,因为在iOS9中选择联想词不会走(textView:shouldChangeTextInRange:replacementText:)这个方法
- (void)textViewDidChange:(UITextView *)textView {
    // textView.markedTextRange == nil 说明当前不是正在打字的高亮状态
    if (textView.markedTextRange == nil) {
        if (textView.text.length > MaxCount) {
            textView.text = [textView.text substringToIndex:MaxCount];
        }
    }
}

你可能感兴趣的:(UITextField和UITextView限制输入字数的方法)