1.声明变量:
@property (nonatomic, strong) UITextField *textField;
2.添加监听:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:self.textField];
3.在监听中,过滤非中文字符,并且限制中文字符长度:
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
//过滤非汉字字符
textField.text = [self filterCharactor:textField.text withRegex:@"[^\u4e00-\u9fa5]"];
if (textField.text.length >= 4) {
textField.text = [textField.text substringToIndex:4];
}
return NO;
}
- (void)textFiledEditChanged:(id)notification{
UITextRange *selectedRange = self.textField.markedTextRange;
UITextPosition *position = [self.textField positionFromPosition:selectedRange.start offset:0];
if (!position) { // 没有高亮选择的字
//过滤非汉字字符
self.textField.text = [self filterCharactor:self.textField.text withRegex:@"[^\u4e00-\u9fa5]"];
if (self.textField.text.length >= 4) {
self.textField.text = [self.textField.text substringToIndex:4];
}
}else { //有高亮文字
//do nothing
}
}
//根据正则,过滤特殊字符
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
NSString *searchText = string;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
return result;
}
4.移除监听:
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}