2009-08-12 17 views
6

¿Hay alguna forma de atrapar todos los eventos de teclado en mi aplicación? Necesito saber si el usuario ingresa algo usando el teclado en mi aplicación (la aplicación tiene múltiples vistas). Pude capturar TouchEvents subclasificando UIWindow pero no pude capturar eventos de teclado.Recibir eventos de teclado de iPhone

Respuesta

13

Uso NSNotificationCenter

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil]; 

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextViewTextDidChangeNotification object: nil]; 

........ 

-(void) keyPressed: (NSNotification*) notification 
{ 
    NSLog([[notification object]text]); 
} 
2

No es una respuesta simple, pero creo que tiene dos enfoques disponibles.

  1. subclase los componentes de entrada (UITextView, UITextField, etc.) como lo ha hecho con el UIWindow.

  2. crear una amplia UITextViewDelegate aplicación (y UITextFieldDelegate) y asignar todos los delegados de campo de entrada a la misma.

+0

Esto es poco complicado ahora e implica mucho trabajo. Esperaba ver algún evento de nivel de aplicación para capturar – iamMobile

10

me escribió acerca de la captura de eventos usando un pequeño programa de UIEvent en mi Blog

Por favor, consulte: Catching Keyboard Events in iOS para más detalles.

Desde el blog mencionado anteriormente:

El truco está en acceder a la memoria GSEventKey estructura directamente y comprobar ciertos bytes saber el código clave y las banderas de la tecla pulsada. Debajo de , el código es casi autoexplicativo y debe colocarse en su subclase UIApplication .

#define GSEVENT_TYPE 2 
#define GSEVENT_FLAGS 12 
#define GSEVENTKEY_KEYCODE 15 
#define GSEVENT_TYPE_KEYUP 11 

NSString *const GSEventKeyUpNotification = @"GSEventKeyUpHackNotification"; 

- (void)sendEvent:(UIEvent *)event 
{ 
    [super sendEvent:event]; 

    if ([event respondsToSelector:@selector(_gsEvent)]) { 

     // Key events come in form of UIInternalEvents. 
     // They contain a GSEvent object which contains 
     // a GSEventRecord among other things 

     int *eventMem; 
     eventMem = (int *)[event performSelector:@selector(_gsEvent)]; 
     if (eventMem) { 

      // So far we got a GSEvent :) 

      int eventType = eventMem[GSEVENT_TYPE]; 
      if (eventType == GSEVENT_TYPE_KEYUP) { 

       // Now we got a GSEventKey! 

       // Read flags from GSEvent 
       int eventFlags = eventMem[GSEVENT_FLAGS]; 
       if (eventFlags) { 

        // This example post notifications only when 
        // pressed key has Shift, Ctrl, Cmd or Alt flags 

        // Read keycode from GSEventKey 
        int tmp = eventMem[GSEVENTKEY_KEYCODE]; 
        UniChar *keycode = (UniChar *)&tmp; 

        // Post notification 
        NSDictionary *inf; 
        inf = [[NSDictionary alloc] initWithObjectsAndKeys: 
         [NSNumber numberWithShort:keycode[0]], 
         @"keycode", 
         [NSNumber numberWithInt:eventFlags], 
         @"eventFlags", 
         nil]; 
        [[NSNotificationCenter defaultCenter] 
         postNotificationName:GSEventKeyUpNotification 
             object:nil 
            userInfo:userInfo]; 
       } 
      } 
     } 
    } 
} 
+1

Consulte ["¿Cómo podría escribir mi respuesta que vincula correctamente los enlaces a un recurso externo?"] (Http://meta.stackexchange.com/questions/94022/how-could -i-write-my-answer-that-links-to-an-external-resource-proper). –

+0

No entiendo lo que tengo -1. Sí, el enlace es a una publicación de mi blog, pero responde completamente esta pregunta. Captura TODOS los eventos del teclado, incluidos Shift, Cmd, Ctrl, Alt. Si es por el uso de Private API, claramente dije que es un ** hack **. No estoy engañando a nadie aquí. – nacho4d

+0

Probablemente porque su respuesta no responde a la pregunta, simplemente apunta a una fuente externa que puede desaparecer, romperse o simplemente cambiar más allá de esta pregunta. Como señala Anna Lear, lea la sección que señaló. La respuesta apunta a lo siguiente como las reglas adecuadas a seguir: - parafrasea el contenido del elemento vinculado (posiblemente omitiendo detalles o ejemplos) - identifica al autor (usted mismo, MSDN, etc.) - alguien podría beneficiarse del responder sin leer el elemento vinculado en absoluto - incluye información para dejar que el lector decida si hacer clic en el enlace vale la pena – Coyote

Cuestiones relacionadas