1. 程式人生 > >iOS 限制輸入框不能輸入中文

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

boa bject sub selector bsp ext val fault def

開發中遇到這個問題,想著還是總結下,剛開始只是限制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;

}

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