iPhone:以编程方式更改键盘语言

标签 iphone iphone-softkeyboard

每当打开 native 键盘时,我都会尝试在我的 iOS 5.x 应用程序上提供不同的语言支持。以编程方式在 native 键盘中提供此语言。有人可以指导我如何支持它吗?我看到了一个 Carbon 框架,但看起来像是用于 Mac 应用程序的。

谢谢。

最佳答案

从 iOS 7 开始,您可以在每个 UIResponder 的基础上执行此操作。 UIResponder 类中有 textInputMode 属性。它是只读的,但文档说:

The text input mode identifies the language and keyboard displayed when this responder is active.

For responders, the system normally displays a keyboard that is based on the user’s language preferences. You can redefine this property and use it to return a different text input mode in cases where you want a responder to use a specific keyboard. The user can still change the keyboard while the responder is active, but switching away to another responder and then back restores the keyboard you specified.

在我的项目中,我创建了 UITextField 的子类,并定义了一个名为 userDefinedKeyboardLanguage 的新属性。我还重写了上面提到的 textInputMode 方法。它看起来类似于以下内容:

- (UITextInputMode *) textInputMode {
    for (UITextInputMode *tim in [UITextInputMode activeInputModes]) {
        if ([[Utilities langFromLocale:userDefinedKeyboardLanguage] isEqualToString:[Utilities langFromLocale:tim.primaryLanguage]]) return tim;
    }
    return [super textInputMode];
}

我的 Utilities 类中还有一个自定义方法 +(NSString *)langFromLocale:(NSString *)locale ,如下所示:

+ (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];
}

现在,我的自定义文本字段类只需将 userDefinedKeyboardLanguage 属性设置为所需的语言即可更改键盘输入语言。

关于iPhone:以编程方式更改键盘语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12595970/

相关文章:

iphone - ASIHTTPRequest代码设计

iphone - 没有带有 UIAlertViewStylePlainTextInput 的键盘?

ios - 如何在IOS模拟器上模拟软键盘点击?

iphone - StopUpdatingLocation 方法不适用于 iOS5

iphone - 核心数据关系错误(不是延迟加载)。关系消失

iphone - 如何将小写字符转换为大写字符?

iPhone iAd 问题?

ios - 如何更改 iOS 中软键盘的显示标题?

iPhone 键盘没有 TextView