如何找到iOS8上使用的当前键盘?
您可以使用以下命令获取iOS设备上安装的键盘列表:
NSUserDefaults *userDeafaults = [NSUserDefaults standardUserDefaults]; NSDictionary * userDefaultsDict = [userDeafaults dictionaryRepresentation]; NSLog(@"%@", userDefaultsDict);
这在控制台中产生了一些东西:
{ ... AppleKeyboards = ( "en_US@hw=US;sw=QWERTY", "es_ES@hw=Spanish - ISO;sw=QWERTY-Spanish", "emoji@sw=Emoji", "com.swiftkey.SwiftKeyApp.Keyboard" ); AppleKeyboardsExpanded = 1; ... }
这告诉我该设备安装了西class牙语,表情符号和SwiftKey键盘,但它没有告诉我键盘出现时将使用哪个键盘。
有办法告诉吗?
这没有公共API,但是我找到了一个解决方案,它需要很少的“灰色区域API”(如果API通常不暴露,我将API定义为“灰色区域”,但可以隐藏几乎没有工作)。
iOS具有以下类: UITextInputMode
该类为您提供了用户可以使用的所有输入方法。 仅当键盘打开时 ,使用以下查询将为您提供当前使用的查询:
UITextInputMode* inputMode = [[[UITextInputMode activeInputModes] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isDisplayed = YES"]] lastObject];
要获取扩展名(或常规Apple键盘)的显示名称,请使用:
[inputMode valueForKey:@"displayName"]
要么
[inputMode valueForKey:@"extendedDisplayName"]
这仅在键盘可见时有效。 所以你必须自己监控输入模式的变化
[[NSNotificationCenter defaultCenter] addObserverForName:UITextInputCurrentInputModeDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"%@", [[[[UITextInputMode activeInputModes] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isDisplayed = YES"]] lastObject] valueForKey:@"extendedDisplayName"]); }); }];
我们实际上需要延迟获取当前输入模式,因为在键盘内部实现使用新值更新系统之前发送通知。 在下一个runloop上获得它很有效。
Leo Natan的答案很棒,但我想补充一点。 您实际上可以随时获取当前输入模式,而不仅仅是键盘打开时,如下所示:
UITextView *textView = [[UITextView alloc] init]; UITextInputMode *inputMode = textView.textInputMode;
请注意,出于某种原因, textView.textInputMode
对于表情符号键盘是nil
。
此外,除了displayName
和extendedDisplayName
,您还可以检索其他键,例如identifier
, normalizedIdentifier
(iOS 8+), hardwareLayout
,…请在此处查看完整的API:
现在我不确定使用其中任何一个比使用App Store批准的displayName
更危险…
@Leo Natan的答案很酷但是当键盘没有显示时它可能会返回nil
。
所以我在这里使用字符串来查找UIKeyboardInputMode
的属性。
我可以告诉你,这可以找到当前的键盘,因为它来自Apple的私有API。
代码在这里:
+ (BOOL)isTheCustomKeyboard { UITextInputMode* inputMode = [UITextInputMode currentInputMode]; if ([inputMode respondsToSelector:NSSelectorFromString(@"identifier")]) { NSString* indentifier = [inputMode performSelector:NSSelectorFromString(@"identifier")]; if ([indentifier isEqualToString: YOUR_APP_ID]) { return YES; } } return NO; }
和更多:
+ (BOOL)isContaintCustomKeyboard { NSArray * inputModes = [UITextInputMode activeInputModes]; for (id inputModel in inputModes) { if ([inputModel respondsToSelector:NSSelectorFromString(@"identifier")]) { NSString* indentifier = [inputModel performSelector:NSSelectorFromString(@"identifier")]; if ([indentifier isEqualToString: YOUR_APP_ID]) { return YES; } } } return NO; }
实际上我们也可以使用displayName
或identifier
等。