当用户在iPhone App中的UITextField中输入值时,如何显示特定的语言键盘?

问题描述:

我想构建一个支持多语言的iPhone应用程序。我希望用我在应用程序设置中从一组语言中选择的语言输入值。因此,它应该显示选定的语言键盘。

I want to build an iPhone Application which supports multi-language. In that I want to input values in the language which user has selected from a set of languages in my application's settings. Accordingly, it should show selected language keyboard.

例如:如果用户从我的应用程序设置中选择了法语。然后在我的应用程序的所有UITextFields中,用户应该能够以法语输入值。因此,当键盘打开时,我需要确保它是法语语言键盘,它每次显示而不是默认语言键盘。

For eg : If user has selected French Language from my application's setting. Then in all the UITextFields of my application, user should be able to input values in French Language. So for that when keyboard opens I need to make sure that it is French Language Keyboard which it shows every time instead of default language keyboard.

所以问题是,当用户根据应用程序设置中选择的语言点击UITextField时,是否可以显示特定的语言键盘?
如果是,那么如何?

So the question is, is It possible to show specific language keyboard whenever user taps on UITextField based on the language selected in the application's settings? If yes then how?

您需要覆盖UITextView的textInputMode

You need to override textInputMode for your UITextView

@implementation UITextView (Localization)

- (UITextInputMode *) textInputMode {
    for (UITextInputMode *inputMode in [UITextInputMode activeInputModes])
    {
        if ([[self langFromLocale:[self localeKey]] isEqualToString:[self langFromLocale:inputMode.primaryLanguage]])
            return inputMode;
    }
    return [super textInputMode];
}


- (NSString*) localeKey
{
    NSArray* lang = [[NSUserDefaults standardUserDefaults]objectForKey:@"AppleLanguages"];
    NSString* currentLang = lang[0];
    return currentLang;
}

- (NSString *)langFromLocale:(NSString *)locale {
    NSRange r = [locale rangeOfString:@"_"];
    if (r.length == 0) r.location = locale.length;
    NSRange r2 = [locale rangeOfString:@"-"];
    if (r2.length == 0) r2.location = locale.length;
    return [[locale substringToIndex:MIN(r.location, r2.location)] lowercaseString];
}

现在你可以改变输入语言:

And you now can chan change input lang:

[[NSUserDefaults standardUserDefaults] setObject:@[@"fr"] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];