UITextField 限制只能输入中文,并限定字数

需求: 多个UITextFiled中的一个UITextFiled 限制只能输入中文, 而且不能超过10个字;其他字符,禁止输入;

方案:添加通知监听,在监听中,过滤字符;

1.声明变量:

@property (nonatomic, strong) UITextField *passwordAgainTF;

@property (nonatomic, strong) UITextField *nameTF; //姓名

@property (nonatomic, strong) UITextField *mobilePhoneTF;

2.在UITextFiled的代理方法中添加监听

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    if (textField == self.nameTF) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:self.nameTF];
     }
     else {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    return YES;
}

3.在代理方法中限制中文字符长度

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.nameTF) {
    
        //过滤非汉字字符
        self.nameTF.text = [self filterCharactor:textField.text withRegex:@"[^\u4e00-\u9fa5]"];
    
        if (self.nameTF.text.length > 10) {
            self.nameTF.text = [textField.text substringToIndex:9];
        
        }
    } 
    return YES;
}

4.实现通知方法

- (void)textFiledEditChanged:(id)notification{
    UITextRange *selectedRange = self.nameTF.markedTextRange;
    UITextPosition *position = [self.nameTF positionFromPosition:selectedRange.start offset:0];

    if (!position) { //// 没有高亮选择的字
        //过滤非汉字字符
        self.nameTF.text = [self filterCharactor:self.nameTF.text withRegex:@"[^\u4e00-\u9fa5]"];
    
        if (self.nameTF.text.length != self.length)     {
        self.length = self.nameTF.text.length;
        }
        else {
        //此方法为我自己封装的提示语
        [self hudShowTextOnly:@"请输入中文,不能包含字母或数字" delay:1 view:KWindow];
        }
    
        if (self.nameTF.text.length > 10) {
            self.nameTF.text = [self.nameTF.text substringToIndex:10];
        }
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

5.私有方法,根据正则,过滤特殊字符

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

你可能感兴趣的:(UITextField 限制只能输入中文,并限定字数)