2011-11-02 21 views
11

Sé que esto se ha preguntado antes, y las únicas respuestas que he visto son "No requiere un teclado externo, ya que va en contra de las pautas de la interfaz de usuario". Sin embargo, quiero usar un pedal como este: http://www.bilila.com/page_turner_for_ipad para cambiar entre páginas en mi aplicación (además de deslizar). Esta página turner simula un teclado y usa las teclas de flecha arriba/abajo.¿Cómo puedo responder a las teclas de flecha del teclado externo?

Así que aquí está mi pregunta: ¿cómo respondo a estos eventos de teclas de flecha? Debe ser posible mientras otras aplicaciones se administran, pero estoy dibujando un espacio en blanco.

Respuesta

21

Para aquellos que buscan una solución en iOS 7, existe una nueva propiedad UIResponder llamada keyCommands. Crear una subclase de UITextView e implementar keyCommands de la siguiente manera ...

@implementation ArrowKeyTextView 

- (id) initWithFrame: (CGRect) frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
    } 
    return self; 
} 

- (NSArray *) keyCommands 
{ 
    UIKeyCommand *upArrow = [UIKeyCommand keyCommandWithInput: UIKeyInputUpArrow modifierFlags: 0 action: @selector(upArrow:)]; 
    UIKeyCommand *downArrow = [UIKeyCommand keyCommandWithInput: UIKeyInputDownArrow modifierFlags: 0 action: @selector(downArrow:)]; 
    UIKeyCommand *leftArrow = [UIKeyCommand keyCommandWithInput: UIKeyInputLeftArrow modifierFlags: 0 action: @selector(leftArrow:)]; 
    UIKeyCommand *rightArrow = [UIKeyCommand keyCommandWithInput: UIKeyInputRightArrow modifierFlags: 0 action: @selector(rightArrow:)]; 
    return [[NSArray alloc] initWithObjects: upArrow, downArrow, leftArrow, rightArrow, nil]; 
} 

- (void) upArrow: (UIKeyCommand *) keyCommand 
{ 

} 

- (void) downArrow: (UIKeyCommand *) keyCommand 
{ 

} 

- (void) leftArrow: (UIKeyCommand *) keyCommand 
{ 

} 

- (void) rightArrow: (UIKeyCommand *) keyCommand 
{ 

} 
+0

¿Funcionará con 'UIWebView'? – Dmitry

+0

@Altaveron la propiedad keyCommands es una propiedad en UIResponder y UIWebView hereda de UIResponder, por lo que no veo ninguna razón por la que no funcione. – amergin

+0

'UIWebView' es un contenedor para muchas subvistas. – Dmitry

9

¡Ordenado! Simplemente utilizo una vista de texto 1x1px y utilizar el método delegado textViewDidChangeSelection:

EDIT: Para iOS 6 que tenía que cambiar la vista del texto a 50x50px (o al menos lo suficiente como para mostrar realmente el texto) para que esto funcione

También pude suprimir el teclado en pantalla cuando el pedal está desconectado.

Este es mi código en viewDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil]; 

UITextView *hiddenTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; 
[hiddenTextView setHidden:YES]; 
hiddenTextView.text = @"aa"; 
hiddenTextView.delegate = self; 
hiddenTextView.selectedRange = NSMakeRange(1, 0); 
[self.view addSubview:hiddenTextView]; 

[hiddenTextView becomeFirstResponder]; 
if (keyboardShown) 
    [hiddenTextView resignFirstResponder]; 

keyboardShown se declara como un bool en mi archivo de cabecera.

A continuación, agregue estos métodos:

- (void)textViewDidChangeSelection:(UITextView *)textView { 

    /******TEXT FIELD CARET CHANGED******/ 

    if (textView.selectedRange.location == 2) { 

     // End of text - down arrow pressed 
     textView.selectedRange = NSMakeRange(1, 0); 

    } else if (textView.selectedRange.location == 0) { 

     // Beginning of text - up arrow pressed 
     textView.selectedRange = NSMakeRange(1, 0); 

    } 

    // Check if text has changed and replace with original 
    if (![textView.text isEqualToString:@"aa"]) 
     textView.text = @"aa"; 
} 

- (void)keyboardWillAppear:(NSNotification *)aNotification { 
    keyboardShown = YES; 
} 

- (void)keyboardWillDisappear:(NSNotification *)aNotification { 
    keyboardShown = NO; 
} 

espero que este código ayuda a otra persona que está buscando una solución a este problema. Sientase libre de usarlo.

+1

funcionó muy bien para mí, pero que tenía que poner el código de inicialización en viewDidAppear no viewDidLoad. – Bryan

+2

Creo que esto lleva a un bucle infinito, porque la configuración de la propiedad 'selectedRange' (en' textViewDidChangeSelection') desencadena otra 'textViewDidChangeSelection', aunque esta idea realmente me ayudó. –

+0

No causará un bucle infinito, ya que 'selectedRange' solo se establece si la ubicación del cursor es 0 o 2. – colincameron

Cuestiones relacionadas