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