Ajuste de la interfaz cuando aparece el teclado para UITextField o UITextView

StackOverflow https://stackoverflow.com/questions/402658

  •  03-07-2019
  •  | 
  •  

Pregunta

Tengo una tabla con cada celda que contiene una etiqueta y un campo de texto. El problema es que cuando voy a editar la última fila, el teclado oculta la parte inferior de la tabla y no puedo ver lo que se está escribiendo. ¿Cómo puedo mover mi interfaz sobre el teclado para ver qué se está escribiendo?

Gracias, Mustafa

¿Fue útil?

Solución

Querrá registrar su viewController para los eventos UIKeyboardDidShowNotification y UIKeyboardWillHideNotification . Cuando obtenga estos, debe ajustar los límites de su tabla; el teclado tiene una altura de 170 píxeles, por lo que solo tiene que reducir o aumentar los límites de la tabla de forma adecuada, y debería ajustarse correctamente al teclado.

Otros consejos

Este problema es complejo dependiendo de su escenario de UI. Aquí discutiré un escenario en el que UITextField o UITextview reside en un UITableViewCell.

  1. Debe usar NSNotificationCenter para detectar el evento UIKeyboardDidShowNotification. consulte http://iosdevelopertips.com/user-interface/adjust -textfield-hidden-by-keyboard.html . Debe reducir el tamaño del marco de UITableView para que ocupe solo el área de la pantalla que no está cubierta por el teclado.

    1. Si toca un UITableViewCell, el sistema operativo colocará automáticamente la celda dentro del área de visualización de UITableView. Pero esto no sucede cuando toca un UITextView o un UITableViewCell incluso si reside en un UITableViewCell.

Necesitas llamar

[myTableView selectRowAtIndexPath:self.indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];` 

para programáticamente " toque " la célula.

Si implementas ambos puntos, verás la posición UITextView / Field justo encima del teclado. Tenga en cuenta que el UITableViewCell donde reside el UITableView / Field no puede ser más alto que el " no cubierto " zona. Si este no es el caso para usted, hay un enfoque diferente para él pero no lo discutiré aquí.

Solo asegúrate de tener suficiente espacio de desplazamiento debajo de eso. Porque según mi conocimiento, el iPhone se ajusta automáticamente y muestra el cuadro de texto enfocado en el momento en que aparece su teclado.

Eliminar / comentar las líneas donde se modifica la altura rect parece resolver el problema. Gracias.

Código modificado:

# define kOFFSET_FOR_KEYBOARD 150.0     // keyboard is 150 pixels height

// Animate the entire view up or down, to prevent the keyboard from covering the author field.
- (void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

// Make changes to the view's frame inside the animation block. They will be animated instead
// of taking place immediately.
CGRect rect = self.view.frame;
CGRect textViewRect = self.textViewBeingEdited.frame;
CGRect headerViewRect = self.headerView.frame;

if (movedUp) {
    // If moving up, not only decrease the origin but increase the height so the view 
    // covers the entire screen behind the keyboard.
    rect.origin.y -= kOFFSET_FOR_KEYBOARD;
    // rect.size.height += kOFFSET_FOR_KEYBOARD;
} else {
    // If moving down, not only increase the origin but decrease the height.
    rect.origin.y += kOFFSET_FOR_KEYBOARD;
    // rect.size.height -= kOFFSET_FOR_KEYBOARD;
}

self.view.frame = rect;
[UIView commitAnimations];

}

     [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWasShown:)
                                                     name:UIKeyboardDidShowNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWasHidden:)
                                                     name:UIKeyboardDidHideNotification
                                                   object:nil];
        keyboardVisible = NO;

- (void)keyboardWasShown:(NSNotification *)aNotification {
    if ( keyboardVisible )
        return;

    if( activeTextField != MoneyCollected)
    {
        NSDictionary *info = [aNotification userInfo];
        NSValue *aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
        CGSize keyboardSize = [aValue CGRectValue].size;

        NSTimeInterval animationDuration = 0.300000011920929;
        CGRect frame = self.view.frame;
        frame.origin.y -= keyboardSize.height-300;
        frame.size.height += keyboardSize.height-50;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        self.view.frame = frame;
        [UIView commitAnimations];

        viewMoved = YES;
    }

    keyboardVisible = YES;
}

- (void)keyboardWasHidden:(NSNotification *)aNotification {
    if ( viewMoved ) 
    {
        NSDictionary *info = [aNotification userInfo];
        NSValue *aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
        CGSize keyboardSize = [aValue CGRectValue].size;

        NSTimeInterval animationDuration = 0.300000011920929;
        CGRect frame = self.view.frame;
        frame.origin.y += keyboardSize.height-300;
        frame.size.height -= keyboardSize.height-50;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        self.view.frame = frame;
        [UIView commitAnimations];

        viewMoved = NO;
    }

    keyboardVisible = NO;
}
tabelview.contentInset =  UIEdgeInsetsMake(0, 0, 210, 0);
[tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:your_indexnumber inSection:Your_section]
                 atScrollPosition:UITableViewScrollPositionMiddle animated:NO];

prueba esto mi codificación, esto te ayudará a ti

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top