2009-09-12 13 views
16

¿Alguien sabe, puedo obtener el idioma de entrada actual y/o el diseño del teclado en la aplicación de iPhone? ¿Puedo recibir una notificación cuando se modificó el idioma de entrada?Detectando el idioma actual de entrada de iPhone

+0

Respuesta más reciente: http://stackoverflow.com/questions/3860553/is-it-possible-to-detect-the-current-keyboard-input-method-on-the-iphone –

+0

Es posible que desee mira este enlace http://razibdeb.wordpress.com/2013/01/30/how-to-check-whether-a-character-is-from-english-language-or-not-in-objective-c/ –

Respuesta

5

Desde la Biblioteca de Apple de referencia - "Getting the Current Language and Locale":

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults]; 
NSArray* languages = [defs objectForKey:@"AppleLanguages"]; 
NSString* preferredLang = [languages objectAtIndex:0]; 
+4

'[NSLocale preferredLanguages] 'es la forma oficial de obtener la lista de idiomas preferidos. Pero creo que @Danya quiere es el nombre del diseño actual del teclado. Eso es otra cosa. –

+0

Exactamente. Necesito cambiar el contenido de la vista dependiendo del idioma de entrada actual. Por lo tanto, necesito tener una forma de obtener el idioma actual del teclado, así como una notificación cuando el usuario presiona el botón del teclado para cambiar el idioma. –

+0

Esto es útil, porque [NSLocale currentLocale] no le proporcionará el idioma de UI del usuario. – leviathan

8

Puede agregar un observador al centro de notificación por defecto:

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(inputModeDidChange:) 
              name:@"UIKeyboardCurrentInputModeDidChangeNotification" 
              object:nil]; 

Este método imprime el idioma de entrada seleccionado en ese momento (como "en_US" o "de_DE"):

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

PERO: ¡Todo lo anterior no está documentado y no debe usarlo en el código de envío!

+0

Explique el voto a la baja. –

+1

Es posible que haya obtenido el neg porque está describiendo código que no se puede enviar con el SDK. –

+1

Interesante, pero no útil, si de hecho no puedo usar el código de "envío". – bentford

1

La forma en que lo haría es el siguiente:

  • Registre su ViewController como oyente a UIApplicationDidBecomeActiveNotification

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];

  • En manejador applicationDidBecomeActive, comprobar el idioma actual usando [NSLocale preferredLanguages] y actuar de acuerdo a esto.

Este enfoque le proporciona lo que desea y es totalmente realizable sin tener que utilizar una API privada.

+0

Esto devuelve el idioma de la interfaz de usuario, no el idioma de entrada/teclado. – nschum

27

En iOS 4.2 y posterior, puede utilizar la clase UITextInputMode para determinar el idioma principal que se utiliza actualmente para la entrada de texto.

[UITextInputMode currentInputMode].primaryLanguage le dará un NSString que representa el código de idioma BCP 47 como "es", "en-US" o "fr-CA".

Puede registrarse para el UITextInputCurrentInputModeDidChangeNotification para recibir una alerta cuando cambie el modo de entrada actual.

(Usted también puede estar interesado en la sesión "Getting Your Apps Ready for China and other Hot New Markets" WWDC, y Internationalization Programming Topics.)

+0

+1 Buena adición a esta publicación anterior. –

+0

Desaprobado desde iOS7. –

+1

Como este método está en desuso en iOS7, es mejor utilizar el método actual de respuesta inmediata ** textInputMode **. Su trabajo es el mismo Ver mi respuesta – kirander

16

Puede pedir actual primer nivel de respuesta (UITextField, UISearchBar, etc.) a través del método UIResponder textInputMode:

// assume you have instance variable pointing to search bar currently entering 
UITextInputMode *inputMode = [self.searchBar textInputMode]; 
NSString *lang = inputMode.primaryLanguage; 
+0

¡Buena respuesta! ... –

1

En línea con las respuestas principales, la siguiente es una solución genérica para obtener el idioma del teclado cada vez que se cambia.Registrarse para la notificación UITextInputCurrentInputModeDidChangeNotification:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inputModeDidChange:) name:UITextInputCurrentInputModeDidChangeNotification object:nil]; 

Luego, en inputModeDidChange

-(void)inputModeDidChange:(NSNotification *)notification { 
    UIView *firstResponder = [UIView currentFirstResponder]; 
    UITextInputMode *currentInputMode = firstResponder.textInputMode; 
    NSString *keyboardLanguage = [currentInputMode primaryLanguage]; 
    NSLog(@"%@", keyboardLanguage); // e.g. en-US 
} 

Dónde currentFirstResponder es de una categoría de UIView para obtener el primer punto de vista de respuesta, como se sugiere en this SO mensaje:

// UIView+Additions.h 
#import <UIKit/UIKit.h> 
@interface UIView (Additions) 
+ (id)currentFirstResponder; 
@end 

Implementación

// UIView+Additions.m 
#import "UIView+Additions.h" 
static __weak id currentFirstResponder; 
@implementation UIView (Additions) 
+ (id)currentFirstResponder { 
    currentFirstResponder = nil; 
    // This will invoke on first responder when target is nil 
    [[UIApplication sharedApplication] sendAction:@selector(findFirstResponder:) 
              to:nil 
             from:nil 
            forEvent:nil]; 
    return currentFirstResponder; 
} 

- (void)findFirstResponder:(id)sender { 
    // First responder will set the static variable to itself 
    currentFirstResponder = self; 
} 
@end 
Cuestiones relacionadas