對(duì)于UITextField控件乃沙, 常規(guī)的屬性用法大家都很熟悉谣蠢, 但依然有一些不常用的“遺珠”屬性班巩,今天來撿撿漏。
需求:
只輸入字母和數(shù)字氮兵, 且字母需要全部大寫
相信一部分同學(xué)會(huì)覺得不好處理裂逐, 是否需要監(jiān)聽UITextFieldTextDidChangeNotification,然后判斷輸入的字符進(jìn)行替換操作泣栈, 第三方搜狗鍵盤很多屏蔽操作無效卜高,要怎么強(qiáng)制屏蔽等等問題。 南片。 不著急掺涛, 一步步處理。
-
強(qiáng)制開啟系統(tǒng)鍵盤
首先疼进,設(shè)置鍵盤類型薪缆,textField.keyboardType = UIKeyboardTypeASCIICapable
其次,設(shè)置代理伞广, 設(shè)置textField.secureTextEntry = YES;
實(shí)現(xiàn)代理方法:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
textField.secureTextEntry = NO;
}
當(dāng)我們?cè)O(shè)置了textField
為密碼模式時(shí)拣帽,系統(tǒng)會(huì)自動(dòng)屏蔽掉第三方鍵盤, 包括搜狗嚼锄, 這樣就不需要我們?nèi)ヮ~外判斷鍵盤類型和模式了减拭, 但此時(shí)我們的需求需要輸入的內(nèi)容明文顯示, 那么在代理方法textFieldDidBeginEditing
內(nèi)区丑, 再改回明文模式即可拧粪。
-
字母連續(xù)大寫
首先,設(shè)置自動(dòng)大寫類型:textField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
其次沧侥, 設(shè)置開啟自動(dòng)校正:textField.autocorrectionType = UITextAutocorrectionTypeYes;
系統(tǒng)有兩個(gè)枚舉屬型:UITextAutocapitalizationType
和 UITextAutocorrectionType
typedef NS_ENUM(NSInteger, UITextAutocapitalizationType) {
UITextAutocapitalizationTypeNone, // 不自動(dòng)大寫
UITextAutocapitalizationTypeWords, // 單詞首字母大寫
UITextAutocapitalizationTypeSentences, // 句子首字母大寫
UITextAutocapitalizationTypeAllCharacters, // 所有祖母大寫
};
typedef NS_ENUM(NSInteger, UITextAutocorrectionType) {
UITextAutocorrectionTypeDefault, // 默認(rèn)
UITextAutocorrectionTypeNo, // 自動(dòng)校正
UITextAutocorrectionTypeYes, // 不自動(dòng)校正
};
根據(jù)這兩個(gè)屬性值可霎, 搭配代理,就可方便的設(shè)置輸入內(nèi)容為字母且連續(xù)大寫了:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
textField.secureTextEntry = NO;
textField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
textField.autocorrectionType = UITextAutocorrectionTypeYes;
}
以上正什, 完結(jié)啥纸。
經(jīng)過測(cè)試新一輪檢測(cè), 發(fā)現(xiàn)這種處理方式有時(shí)候還是無法完全實(shí)現(xiàn)強(qiáng)制屏蔽第三方鍵盤婴氮, 那可看情況使用下面的代碼:
-
全局屏蔽第三方鍵盤
在AppDelegate.m
中實(shí)現(xiàn)下面這個(gè)方法
- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier{
if ([extensionPointIdentifier isEqualToString:@"com.apple.keyboard-service"]) {
return NO;
}
return YES;
}