2012-02-17 3 views
5

Quiero crear una vista, como el cuadro de diálogo compartido de la aplicación Facebook o Twitter, por ejemplo, donde solo hay una UITextView y un teclado permanente. Puedo ver cómo comenzar con el teclado visible desde this answer, pero no estoy seguro de cómo ajustar el tamaño del UITextView para que encaje exactamente encima del teclado. Si no lo hago, el texto puede ocultarse debajo del teclado, lo cual es incómodo.¿Cómo creo un UITextView que se ajuste exactamente sobre el teclado?

Respuesta

3

He encontrado un ejemplo de código útil en la documentación de Apple para esto: https://developer.apple.com/library/ios/#samplecode/KeyboardAccessory/Introduction/Intro.html

Aquí está el código que terminó con. No me preocupa el ocultamiento del teclado, ya que, desde mi punto de vista, el teclado nunca debería esconderse.

- (void)viewWillAppear:(BOOL)flag 
{ 
    [super viewWillAppear:flag]; 

    // Listen for the keyboard to show up so we can get its height 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; 

    // Set focus on the text view to display the keyboard immediately 
    [self.textView becomeFirstResponder]; 
} 
- (void)keyboardWillShow:(NSNotification *)notification 
{ 
    /* 
    Reduce the size of the text view so that it's not obscured by the keyboard. 
    */ 

    NSDictionary *userInfo = [notification userInfo]; 

    // Get the origin of the keyboard when it's displayed. 
    NSValue* keyboardFrame = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]; 

    // Get the top of the keyboard as the y coordinate of its origin in self's view's 
    // coordinate system. The bottom of the text view's frame should align with the 
    // top of the keyboard's final position. 
    CGRect keyboardRect = [keyboardFrame CGRectValue]; 
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; 

    // Set the text view's frame height as the distance from the top of the view bounds 
    // to the top of the keyboard 
    CGFloat keyboardTop = keyboardRect.origin.y; 
    CGRect newTextViewFrame = self.view.bounds; 
    newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y; 
    self.textView.frame = newTextViewFrame; 
} 
0

puedo encontrar esta página siempre es bastante útil - que muestra todos los tamaños importantes, por lo que es fácil de calcular el tamaño que necesita:

http://www.idev101.com/code/User_Interface/sizes.html

+2

No todos los teclados son del mismo tamaño. "Chino - Simplificado (trazo)", por ejemplo. –

3

Puede suscribirse a UIKeyboardWillShowNotification. La notificación incluye el marco del teclado, por lo que puede ajustar el tamaño de la vista para que se ajuste al espacio restante.

2

Usted puede obtener el tamaño del teclado, así:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardIsUp:) name:UIKeyboardDidShowNotification object:nil]; 

- (void)keyboardIsUp:(NSNotification *)notification{ 

    CGSize keyboardSize = [self.view convertRect:[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] toView:nil].size; 
    NSLog(@"%f", keyboardSize.height); 
} 

modo horizontal [EDIT]

lo probé en el iPas simulador y devolverlo 264 en el modo de retrato de un teclado QWERTY, pero cuando inicia la aplicación o gira al modo horizontal, devuelve 1024. Por lo tanto, es posible que deba solicitar el ancho en lugar de la altura en modo horizontal ...

[EDITAR]

Gracias al comentario de Rob mayoff no hay ningún problema con el modo de paisaje más

[EDIT]

Ésta no es la mejor forma de hacerlo, pero que da una idea. Voy a echar un vistazo atrás en ello más tarde

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil]; 

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

    CGSize size = [self.view convertRect:self.view.frame toView:nil].size; 
    CGFloat width = size.width; 
    CGFloat height = 40; 
    CGFloat x = 0; 
    CGFloat y = size.height+40; 

    aboveKBView = [[[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)] autorelease]; 
    [aboveKBView setBackgroundColor:[UIColor greenColor]]; 
    [self.view addSubview:aboveKBView]; 
} 

- (void)keyboardWillHide:(NSNotification *)notification{ 
    [aboveKBView setHidden:YES]; 
} 

- (void)keyboardWillShow:(NSNotification *)notification{ 
    NSLog(@"keyboardIsUp"); 

    CGSize keyboardSize = [self.view convertRect:[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] toView:nil].size; 

    CGSize size = [self.view convertRect:self.view.frame toView:nil].size; 
    CGFloat width = size.width; 
    CGFloat height = 40; 
    CGFloat x = 0; 
    CGFloat y = size.height-(keyboardSize.height+height); 

    [aboveKBView setFrame:CGRectMake(x, y, width, height)]; 
    [aboveKBView setHidden:NO];  
} 
+0

El marco en la notificación está en coordenadas globales. Necesita convertirlo al sistema de coordenadas apropiado usando algo como '[myView convertRect: keyboardFrame fromView: nil]'. –

+0

Gracias por la punta –

+0

Eso funciona para obtener el tamaño, pero todavía tengo problemas para configurar el UITextView a la altura correcta. En el código a continuación frame.size.heigh es 367, y keyboardHeight es 216, pero por alguna razón cuando llamo a setFrame hay espacio entre la vista de texto y el teclado. FYI, estoy configurando el observador y llamando '[self.textView becomeFirstResponder]' en 'viewWillAppear'. –

0

probar este

en viewDidLoad:

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

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

y añadir a estos métodos.

- (void) keyboardWillShow: (NSNotification*) aNotification; 
{ 

    [UIView beginAnimations:nil context:NULL]; 

    [UIView setAnimationDuration:0.3]; 

    CGRect rect = [[self view] frame]; 

    rect.origin.y -= 60; 

    [[self view] setFrame: rect]; 

    [UIView commitAnimations]; 

} 

- (void) keyboardWillHide: (NSNotification*) aNotification; 
{ 

    [UIView beginAnimations:nil context:NULL]; 

    [UIView setAnimationDuration:0.3]; 

    CGRect rect = [[self view] frame]; 

    rect.origin.y += 60; 

    [[self view] setFrame: rect]; 

    [UIView commitAnimations]; 
} 
Cuestiones relacionadas