iOS 限制输入框不能输入中文


开发中遇到这个问题,想着还是总结下,刚开始只是限制UITextField的键盘为

UIKeyboardTypeASCIICapable,可是当用户切换了中文键盘后依然没解决问题,于是我给输入框加了监听事件,获取输入框最新的输入内容,检测输入的内容中是否含有中文,如果有中文就替换成空字符串,具体实现如下:

 

infoView.userTF.keyboardType = UIKeyboardTypeASCIICapable;

 //监听输入内容

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)

                                                name:@"UITextFieldTextDidChangeNotification"

                                              object:infoView.userTF];

 

-(void)textFiledEditChanged:(NSNotification*)notification

{

    UITextField*textField = notification.object;

    NSString*str = textField.text;

    for (int i = 0; i<str.length; i++)

    {

        NSString*string = [str substringFromIndex:i];

        NSString *regex = @"[\u4e00-\u9fa5]{0,}$"; // 中文

        // 2、拼接谓词

        NSPredicate *predicateRe1 = [NSPredicate predicateWithFormat:@"self matches %@", regex];

        // 3、匹配字符串

        BOOL resualt = [predicateRe1 evaluateWithObject:string];

        

        if (resualt)

        {

    //是中文替换为空字符串

            str =  [str stringByReplacingOccurrencesOfString:[str substringFromIndex:i] withString:@""];

 

        }

    }

    textField.text = str;

}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM