在日常開發(fā)中,可能某個(gè) UITextField
只能輸入數(shù)字狐史,但是因?yàn)榘惭b了第三方鍵盤(搜狗步氏、百度等)會(huì)受到影響滑沧,需要禁用第三方鍵盤。
禁用第三方鍵盤需要在 AppDelegate.m
中實(shí)現(xiàn)以下代碼
- (BOOL)application:(UIApplication *)application
shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier
{
if ([extensionPointIdentifier isEqualToString:@"com.apple.keyboard-service"]) {
return NO;
}
return YES;
}
這樣就全局禁用了第三方鍵盤躬它,下面針對(duì)某個(gè) UITextField
進(jìn)行禁用第三方鍵盤
對(duì)某個(gè) UITextField
禁用第三方鍵盤
-
給
UITextField
創(chuàng)建一個(gè)分類腾啥,然后在分類的 .h 文件中添加一個(gè)實(shí)例對(duì)象屬性yxc_usingSystemKeyboard
和一個(gè)類對(duì)象屬性yxc_globalUsingSystemKeyboard
@property (nonatomic, assign) BOOL yxc_usingSystemKeyboard; /**< 使用系統(tǒng)鍵盤 */ @property (nonatomic, assign, class) BOOL yxc_globalUsingSystemKeyboard; /**< 全局是否使用系統(tǒng)鍵盤,主動(dòng)設(shè)置無效 */
-
關(guān)聯(lián)屬性
- (void)setYxc_usingSystemKeyboard:(BOOL)yxc_usingSystemKeyboard { objc_setAssociatedObject(self, @selector(yxc_usingSystemKeyboard), @(yxc_usingSystemKeyboard), OBJC_ASSOCIATION_ASSIGN); } - (BOOL)yxc_usingSystemKeyboard { NSNumber *yxc_usingSystemKeyboard = objc_getAssociatedObject(self, @selector(yxc_usingSystemKeyboard)); return [yxc_usingSystemKeyboard boolValue]; } + (void)setYxc_globalUsingSystemKeyboard:(BOOL)yxc_globalUsingSystemKeyboard { objc_setAssociatedObject(self, @selector(yxc_globalUsingSystemKeyboard), @(yxc_globalUsingSystemKeyboard), OBJC_ASSOCIATION_ASSIGN); } + (BOOL)yxc_globalUsingSystemKeyboard { NSNumber *yxc_globalUsingSystemKeyboard = objc_getAssociatedObject(self, @selector(yxc_globalUsingSystemKeyboard)); return [yxc_globalUsingSystemKeyboard boolValue]; }
-
監(jiān)聽
UITextFieldTextDidBeginEditingNotification
和UITextFieldTextDidEndEditingNotification
通知[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidBeginEdit:) name:UITextFieldTextDidBeginEditingNotification object:self]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidEndEdit:) name:UITextFieldTextDidEndEditingNotification object:self];
-
在監(jiān)聽到
UITextFieldTextDidBeginEditingNotification
和UITextFieldTextDidEndEditingNotification
通知對(duì)yxc_globalUsingSystemKeyboard
值修改- (void)textFieldDidBeginEdit:(NSNotification *)notification { UITextField.yxc_globalUsingSystemKeyboard = self.yxc_usingSystemKeyboard; } - (void)textFieldDidEndEdit:(NSNotification *)notification { UITextField.yxc_globalUsingSystemKeyboard = NO; }
-
AppDelegate
中application:shouldAllowExtensionPointIdentifier:
方法中修改- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier { if ([extensionPointIdentifier isEqualToString:@"com.apple.keyboard-service"]) { if (UITextField.yxc_globalUsingSystemKeyboard) { return NO; } } return YES; }
通過對(duì)某個(gè)
UITextField
實(shí)例對(duì)象設(shè)置yxc_usingSystemKeyboard
屬性值為YES
后就對(duì)某個(gè)UITextField
禁用了第三方鍵盤.效果:
在這里冯吓,第一個(gè)輸入框默認(rèn)的樣式倘待,不禁用第三方鍵盤,第二個(gè)輸入框禁用第三方鍵盤并且設(shè)置鍵盤樣式為 UIKeyboardTypeNumberPad