TextField输入限制的正确方式

首先添加一个文本改变的触发事件
[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 > kMaxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:kMaxLength];
            if (rangeIndex.length == 1) {
                textField.text = [toBeString substringToIndex:kMaxLength];
            }else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, kMaxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}
这样就ok啦

你可能感兴趣的:(TextField输入限制的正确方式)