检测当前的iPhone输入语言

18 iphone keyboard

有谁知道,我可以在iPhone应用程序中获得当前的输入语言和/或键盘布局吗?输入语言更改后,我还可以收到通知吗?

Vin*_*ble 29

在iOS 4.2及更高版本中,您可以使用UITextInputMode该类来确定当前用于文本输入的主要语​​言.

[UITextInputMode currentInputMode].primaryLanguage将为您提供NSString代表BCP 47语言代码,例如"es","en-US"或"fr-CA".

UITextInputCurrentInputModeDidChangeNotification当前输入模式改变时,您可以注册要发出警报.

(您可能也对"为中国和其他热门新市场准备应用程序" WWDC会议和国际化编程主题感兴趣.)


kir*_*der 17

您可以通过UIResponder方法textInputMode询问当前的第一响应者(UITextField,UISearchBar等):

// assume you have instance variable pointing to search bar currently entering
UITextInputMode *inputMode = [self.searchBar textInputMode];
NSString *lang = inputMode.primaryLanguage;
Run Code Online (Sandbox Code Playgroud)


Nik*_*uhe 8

您可以将观察者添加到默认通知中心:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(inputModeDidChange:)
                                             name:@"UIKeyboardCurrentInputModeDidChangeNotification"
                                           object:nil];
Run Code Online (Sandbox Code Playgroud)

此方法打印当前选定的输入语言(如"en_US""de_DE"):

- (void)inputModeDidChange:(NSNotification*)notification
{
    id obj = [notification object];
    if ([obj respondsToSelector:@selector(inputModeLastUsedPreference)]) {
        id mode = [obj performSelector:@selector(inputModeLastUsedPreference)];
        NSLog(@"mode: %@", mode);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是:以上所有内容均未记录,您不应在运输代码中使用它!

  • 我仍然没有得到它...一些反向工程信息的三个downvotes明确表明它不适用于运送应用程序.Downvoters,您对这个答案中的信息感到不满吗? (6认同)
  • @Vincent Gable:请注意,这个答案是在"UITextInputMode"尚未推出的时候编写的(iOS 4.2,2010年11月发布). (2认同)

Ale*_*lds 5

从Apple参考库 - " 获取当前语言和区域设置 ":

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];
Run Code Online (Sandbox Code Playgroud)

  • `[NSLocale preferredLanguages]`是获取首选实验室列表的官方方式.但我认为@Danya想要的是当前键盘布局的名称.那是别的. (5认同)