iOS开发时,有时候我们需要对输入框的位数做出合理的限制。对于UITextField,可通过监听UIControlEventEditingChanged 做出合理的位数限制;UITextView则要实现其代理 -textViewDidChange:对其位数进行限制,此处就不再赘述。
//检测输入变化
[self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- (void)textFieldDidChange:(UITextField *)textField {
if (textField == self.textField) {
//对UITextField字数限制,比如5个字。
static NSUInteger maxLength = 5;
NSString *inputText = textField.text;
//获取高亮部分
UITextRange *markedTextRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:markedTextRange.start offset:0];
//没用高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position || !markedTextRange) {
if (inputText.length > maxLength) {
NSRange rangeIndex = [inputText rangeOfComposedCharacterSequenceAtIndex:maxLength];
if (rangeIndex.length == 1) {
textField.text = [inputText substringToIndex:maxLength];
} else {
NSRange range = [inputText rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
textField.text = [inputText substringWithRange:range];
}
}
}
}
}