您的位置:首页 > 产品设计 > UI/UE

iOS UITextField 限制只能输入中文

2016-09-27 18:26 483 查看
需求:  UITextFiled 限制只能输入4个中文;一起一切字符,禁止输入;

解决方案:添加监听,在监听中,过滤字符;

上干货:

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];
}


5,Over;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息