TextField限制只能输入汉字并且限制输入字数

2016-08-26  本文已影响206人  小雨hahaha

首先在建立textfield的时候要给当前的视图添加一个通知

[[NSNotificationCenter defaultCenter] mdf_safeAddObserver:self selector:@selector(textFieldDidChange) name:UITextFieldTextDidChangeNotification object:nil];

其次就是写这个方法了

- (void)textFieldDidChange
{        
    UITextRange *selectedRange = [self.contentTextField markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [self.contentTextField positionFromPosition:selectedRange.start offset:0];
    
    //如果在变化中是高亮部分在变,就不判断了
    if (selectedRange && pos) {
        return;
    }
    
    NSString *replaceStr = [self.contentTextField.text mdf_safeSubstringFromIndex:self.tempStr.length];
    if (self.inputType == QTKEnterPriseBaseInfoInputTypeChineseCharacter) {
        if (replaceStr.length) {
            // 只能输入中文
            NSString *regex = @"[\\u4e00-\\u9fa5]+$";
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
            if (![pred evaluateWithObject:replaceStr]) {
                [SVProgressHUD showInfoWithStatus:@"只能输入汉字"];
                self.contentTextField.text = self.tempStr;
                return;
            }
        }
    }
    
    if (self.contentTextField.text.length > self.inputLength && self.inputLength) {
        self.contentTextField.text = [self.contentTextField.text mdf_safeSubstringToIndex:self.inputLength];
        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"只能输入%@个字", @(self.inputLength)]];
    }
  self.tempStr = self.contentTextField.text;
}
上一篇下一篇

猜你喜欢

热点阅读