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