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;

}

原文地址:https://www.cnblogs.com/cui-cui/p/7545692.html