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

首先在建立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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 翻译自“Collection View Programming Guide for iOS” 0 关于iOS集合视...
    lakerszhy阅读 3,920评论 1 22
  • 1.OC里用到集合类是什么? 基本类型为:NSArray,NSSet以及NSDictionary 可变类型为:NS...
    轻皱眉头浅忧思阅读 1,394评论 0 3
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,242评论 25 708
  • 2017.02.22 可以练习,每当这个时候,脑袋就犯困,我这脑袋真是神奇呀,一说让你做事情,你就犯困,你可不要太...
    Carden阅读 1,373评论 0 1
  • 2015年6月17日,尚未拿到毕业证书的我,怀着无比的期待、兴致勃勃的走向了社会,踏上一名平台产品经理之路。历经两...
    产品汪的修炼阅读 299评论 10 5