- (void)textFieldDidChange:(UITextField *)textField{
UITextRange *selectedRange = textField.markedTextRange;
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
if (!position) {
// 没有高亮选择的字
// 1. 过滤非汉字、字母、数字字符
self.textField.text = [self filterCharactor:textField.text withRegex:@"[^a-zA-Z0-9\u4e00-\u9fa5]"];
// 2. 截取
if (self.textField.text.length >= 12) {
self.textField.text = [self.textField.text substringToIndex:12];
}
} else {
// 有高亮选择的字 不做任何操作
}
}
// 过滤字符串中的非汉字、字母、数字
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
NSString *filterText = string;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
NSString *result = [regex stringByReplacingMatchesInString:filterText options:NSMatchingReportCompletion range:NSMakeRange(0, filterText.length) withTemplate:@""];
return result;
}
来自:http://www.jianshu.com/p/bda5e198260f
來源:简书
网友评论