iOS之UITextField限制只能输入汉字

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

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,107评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,993评论 6 342
  • 一个人 在这恍惚间举手无措的日子游荡 徐风、暖阳、落英、草场 傍晚的游人不多 三三两两 却无人走近 更嗅不到半点有...
    溪小白_M阅读 137评论 0 0
  • 关于小程序的入口 在Android和iOS最新版本(6.5.3)的微信中,必须要使用过一次小程序,才会在发现栏中最...
    韩小凯阅读 1,310评论 0 3
  • 每当我看到别人的白发, 仿佛那是父母的身影显现, 把我内心的思念, 一次又一次从记忆之门开启。 我是多么地想念, ...
    小剧在成长阅读 149评论 2 2