¿Cómo puedo hacer un movimiento UITextField cuando está presente el teclado - sobre cómo comenzar a editar?

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

Pregunta

Con el SDK de iOS:

Tengo un UIView con UITextFields que traen un teclado. Lo necesito para ser capaz de:

  1. Permitir el desplazamiento de los contenidos de la UIScrollView para ver los otros campos de texto una vez que el teclado se crió

  2. Automáticamente "salto" (desplazándose hacia arriba) o acortando

Sé que necesito un UIScrollView. He intentado cambiar la clase de mi UIView a un UIScrollView pero sigo siendo incapaz de desplazarse a los cuadros de texto hacia arriba o hacia abajo.

¿Es necesario tanto un UIView y una UIScrollView? Hace uno dentro del otro?

Lo que necesita ser implementada con el fin de desplazarse automáticamente al campo de texto activo?

Lo ideal es que gran parte de la configuración de los componentes como sea posible se hará en el Interface Builder. Me gustaría sólo para escribir código para lo que necesite.

Nota:. La UIView (o UIScrollView) que estoy trabajando es criado por una barra de pestañas (UITabBar), lo que necesita para funcionar con normalidad


Edit: Estoy añadiendo la barra de desplazamiento sólo para cuando el teclado aparece. A pesar de que no se necesita, me siento como que proporciona una interfaz mejor, porque entonces el usuario puede desplazarse y cambiar los cuadros de texto, por ejemplo.

Lo tengo trabajo donde puedo cambiar el tamaño del marco de la UIScrollView cuando el teclado va hacia arriba y hacia abajo. Simplemente estoy usando:

-(void)textFieldDidBeginEditing:(UITextField *)textField { 
    //Keyboard becomes visible
    scrollView.frame = CGRectMake(scrollView.frame.origin.x, 
                     scrollView.frame.origin.y, 
scrollView.frame.size.width,
scrollView.frame.size.height - 215 + 50);   //resize
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
   //keyboard will hide
    scrollView.frame = CGRectMake(scrollView.frame.origin.x, 
       scrollView.frame.origin.y, 
     scrollView.frame.size.width,
      scrollView.frame.size.height + 215 - 50); //resize
}

Sin embargo, esto no automáticamente "subir" o centro de los campos de texto más bajos en la zona visible, que es lo que realmente me gustaría.

¿Fue útil?

Solución

  1. Sólo se necesitará un ScrollView si el contenido que tiene ahora no caben en la pantalla del iPhone. (Si va a añadir el ScrollView como el supervista de los componentes. Sólo para hacer la TextField desplazarse hacia arriba cuando el teclado aparece, entonces no es necesario.)

  2. Para que muestra la textfields sin ser oculto por el teclado, la forma estándar es mover hacia arriba / abajo de la vista que tiene campos de texto cuando se muestra el teclado.

Aquí hay algunos ejemplos de código:

#define kOFFSET_FOR_KEYBOARD 80.0

-(void)keyboardWillShow {
    // Animate the current view out of the way
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)keyboardWillHide {
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
    if ([sender isEqual:mailTf])
    {
        //move the main view, so that the keyboard does not hide it.
        if  (self.view.frame.origin.y >= 0)
        {
            [self setViewMovedUp:YES];
        }
    }
}

//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // if you want to slide up the view

    CGRect rect = self.view.frame;
    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
    }
    else
    {
        // revert back to the normal state.
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.view.frame = rect;

    [UIView commitAnimations];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];

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

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                             name:UIKeyboardWillShowNotification
                                           object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                             name:UIKeyboardWillHideNotification
                                           object:nil];
}

Otros consejos

También estaba teniendo una gran cantidad de emisión con una composición de UIScrollView UITextFields múltiple, de los cuales, uno o más de ellos quedar oculto tras el teclado cuando se están editando.

Aquí hay algunas cosas a tener en cuenta si su UIScrollView no se desplaza correctamente.

1) Asegúrese de que su contentSize es mayor que el tamaño del marco UIScrollView. La manera de entender UIScrollViews es que el UIScrollView es como una ventana de visualización del contenido se define en la contentSize. Por eso, cuando el fin de la UIScrollview para desplazarse en cualquier lugar, la contentSize debe ser mayor que el UIScrollView. Si no, no hay necesidad de desplazarse, ya que todo se define en la contentSize ya es visible. Por cierto, por defecto = contentSize CGSizeZero.

2) Ahora que usted entiende que el UIScrollView es realmente una ventana a su "contenido", la manera de garantizar que el teclado no está oscureciendo su visión UIScrollView's "ventana" sería la de cambiar el tamaño de la UIScrollView de manera que cuando el teclado está Actualmente, tienes la ventana UIScrollView dimensionada para sólo el frame.size.height UIScrollView original menos la altura del teclado. Esto asegurará que la ventana es sólo eso pequeña área visible.

3) Aquí está el truco: Cuando he implementado por primera vez este pensé que tendría que obtener la CGRect del campo de texto editado y llamar UIScrollView's método scrollRecToVisible. He implementado el método UITextFieldDelegate textFieldDidBeginEditing con la llamada al método scrollRecToVisible. En realidad, esto trabajó con un efecto secundario raro que el desplazamiento sería Ajustar el UITextField en su posición. Durante mucho tiempo yo no podía entender lo que era. Entonces le comenté a cabo el método textFieldDidBeginEditing Delegado y todo el trabajo !! (???). Al final resultó que, creo que la realidad UIScrollView implícitamente trae la UITextField editado en ese momento en la ventana visible de forma implícita. Mi aplicación del método UITextFieldDelegate y la posterior llamada a la scrollRecToVisible era redundante y fue la causa del extraño efecto secundario.

Así que aquí están los pasos para desplazarse adecuadamente su UITextField en un UIScrollView en su lugar cuando aparezca el teclado.

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad 
{
    [super viewDidLoad];

    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:self.view.window];
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:self.view.window];
    keyboardIsShown = NO;
    //make contentSize bigger than your scrollSize (you will need to figure out for your own use case)
    CGSize scrollContentSize = CGSizeMake(320, 345);
    self.scrollView.contentSize = scrollContentSize;
}

- (void)keyboardWillHide:(NSNotification *)n
{
    NSDictionary* userInfo = [n userInfo];

    // get the size of the keyboard
    CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;


    // resize the scrollview
    CGRect viewFrame = self.scrollView.frame;
    // I'm also subtracting a constant kTabBarHeight because my UIScrollView was offset by the UITabBar so really only the portion of the keyboard that is leftover pass the UITabBar is obscuring my UIScrollView.
    viewFrame.size.height += (keyboardSize.height - kTabBarHeight);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [self.scrollView setFrame:viewFrame];
    [UIView commitAnimations];

    keyboardIsShown = NO;
}

- (void)keyboardWillShow:(NSNotification *)n
{
    // This is an ivar I'm using to ensure that we do not do the frame size adjustment on the `UIScrollView` if the keyboard is already shown.  This can happen if the user, after fixing editing a `UITextField`, scrolls the resized `UIScrollView` to another `UITextField` and attempts to edit the next `UITextField`.  If we were to resize the `UIScrollView` again, it would be disastrous.  NOTE: The keyboard notification will fire even when the keyboard is already shown.
    if (keyboardIsShown) {
        return;
    }

    NSDictionary* userInfo = [n userInfo];

    // get the size of the keyboard
    CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    // resize the noteView
    CGRect viewFrame = self.scrollView.frame;
    // I'm also subtracting a constant kTabBarHeight because my UIScrollView was offset by the UITabBar so really only the portion of the keyboard that is leftover pass the UITabBar is obscuring my UIScrollView.
    viewFrame.size.height -= (keyboardSize.height - kTabBarHeight);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [self.scrollView setFrame:viewFrame];
    [UIView commitAnimations];
    keyboardIsShown = YES;
}
  1. Registrar para las notificaciones de teclado en viewDidLoad
  2. Eliminar el registro de los nofitications teclado en viewDidUnload
  3. Asegúrese de que el contentSize se establece y mayor que su UIScrollView en viewDidLoad
  4. reducir el UIScrollView cuando está presente el teclado
  5. volver el UIScrollView cuando el teclado desaparece.
  6. Utilice una Ivar para detectar si el teclado ya se muestra en la pantalla ya que las notificaciones de teclado se envían cada vez que un UITextField se pestañas, incluso si el teclado ya está presente para evitar encoge el UIScrollView cuando está ya encogido

Una cosa a tener en cuenta es que el UIKeyboardWillShowNotification se disparará aunque cuando el teclado ya está en la pantalla cuando salta en otra UITextField. Me ocupé de esto mediante el uso de una Ivar para evitar el cambio de tamaño del UIScrollView cuando el teclado está en la pantalla es. Sin querer cambiar el tamaño de la UIScrollView cuando el teclado está ya allí sería desastroso!

Hope este código guarda algunos de ustedes mucho dolor de cabeza.

En realidad es mejor sólo para usar la aplicación de Apple, según lo dispuesto en el docs . Sin embargo, el código que proporcionan es defectuoso. Vuelva a colocar la parte que se encuentra en keyboardWasShown: justo por debajo de los comentarios a la siguiente:

NSDictionary* info = [aNotification userInfo];
CGRect keyPadFrame=[[UIApplication sharedApplication].keyWindow convertRect:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] fromView:self.view];
CGSize kbSize =keyPadFrame.size;
CGRect activeRect=[self.view convertRect:activeField.frame fromView:activeField.superview];
CGRect aRect = self.view.bounds;
aRect.size.height -= (kbSize.height);

CGPoint origin =  activeRect.origin;
origin.y -= backScrollView.contentOffset.y;
if (!CGRectContainsPoint(aRect, origin)) {
    CGPoint scrollPoint = CGPointMake(0.0,CGRectGetMaxY(activeRect)-(aRect.size.height));
    [backScrollView setContentOffset:scrollPoint animated:YES];
}

Los problemas con el código de Apple son los siguientes: (1) Siempre calcular si el punto está dentro del marco de la vista, pero es un ScrollView, por lo que ya pueden haber desplazado y hay que tener en cuenta que el desplazamiento:

origin.y -= scrollView.contentOffset.y

(2) Se desplazan la contentOffset por la altura del teclado, pero queremos lo contrario (queremos cambiar el contentOffset por la altura que es visible en la pantalla, no lo que no lo es):

activeField.frame.origin.y-(aRect.size.height)

En textFieldDidBeginEditting y en textFieldDidEndEditing llamar a la función [self animateTextField:textField up:YES] este modo:

-(void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    [self animateTextField:textField up:YES]; 
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField:textField up:NO];
}

-(void)animateTextField:(UITextField*)textField up:(BOOL)up
{
    const int movementDistance = -130; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed

    int movement = (up ? movementDistance : -movementDistance); 

    [UIView beginAnimations: @"animateTextField" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

Espero que este código le ayudará.

En Swift 2

func animateTextField(textField: UITextField, up: Bool) 
{
     let movementDistance:CGFloat = -130
     let movementDuration: Double = 0.3

     var movement:CGFloat = 0
     if up 
     {
         movement = movementDistance
     }
     else 
     {
         movement = -movementDistance
     }
     UIView.beginAnimations("animateTextField", context: nil)
     UIView.setAnimationBeginsFromCurrentState(true)
     UIView.setAnimationDuration(movementDuration)
     self.view.frame = CGRectOffset(self.view.frame, 0, movement)
     UIView.commitAnimations()
}


func textFieldDidBeginEditing(textField: UITextField) 
{
    self.animateTextField(textField, up:true)
}

func textFieldDidEndEditing(textField: UITextField) 
{
    self.animateTextField(textField, up:false)
}

SWIFT 3

 func animateTextField(textField: UITextField, up: Bool)
    {
        let movementDistance:CGFloat = -130
        let movementDuration: Double = 0.3

        var movement:CGFloat = 0
        if up
        {
            movement = movementDistance
        }
        else
        {
            movement = -movementDistance
        }
        UIView.beginAnimations("animateTextField", context: nil)
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.setAnimationDuration(movementDuration)
        self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
        UIView.commitAnimations()
    }


    func textFieldDidBeginEditing(textField: UITextField)
    {
        self.animateTextField(textField: textField, up:true)
    }

    func textFieldDidEndEditing(textField: UITextField)
    {
        self.animateTextField(textField: textField, up:false)
    }

Sólo el uso de campos de texto:

1a) Usando Interface Builder: Seleccionar Todos los campos de texto => Editar => Insertar en => ScrollView

1b) incrustar manualmente TextFields en UIScrollView llamados ScrollView

2) Conjunto UITextFieldDelegate

3) Ajuste cada textField.delegate = self; (o hacer conexiones en Interface Builder)

4) Copiar / pegar:

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    CGPoint scrollPoint = CGPointMake(0, textField.frame.origin.y);
    [scrollView setContentOffset:scrollPoint animated:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [scrollView setContentOffset:CGPointZero animated:YES];
}

Solución universal , Aquí fue mi enfoque para implementar IQKeyboardManager .

introducir descripción de la imagen aquí

Paso 1: - I Añadido notificaciones globales de UITextField, UITextView y UIKeyboard en una clase Singleton. Lo llamo IQKeyboardManager .

Paso 2: - Si se encuentran las notificaciones UIKeyboardWillShowNotification, UITextFieldTextDidBeginEditingNotification o UITextViewTextDidBeginEditingNotification, que tratan de conseguir topMostViewController ejemplo de la jerarquía UIWindow.rootViewController. Con el fin de descubrir adecuadamente UITextField / UITextView en él, marco de topMostViewController.view necesita ser ajustado.

Paso 3: -. I calculada esperada distancia de movimiento de topMostViewController.view con respecto a la primera respondió UITextField / UITextView

Paso 4: - I trasladó topMostViewController.view.frame arriba / abajo de acuerdo a la distancia medida que se espera

.

Paso 5: -. Si se encuentra UIKeyboardWillHideNotification, UITextFieldTextDidEndEditingNotification o notificación UITextViewTextDidEndEditingNotification, vuelvo a tratar de conseguir topMostViewController ejemplo de la jerarquía UIWindow.rootViewController

Paso 6: -. I calcula la distancia perturbado de topMostViewController.view que necesita ser restaurado a su posición original

Paso 7: -. Restauré topMostViewController.view.frame en función de la distancia a perturbado

Paso 8: - IQKeyboardManager instancia de clase de carga de la aplicación, por lo que cada UITextField / UITextView en la aplicación ajustará automáticamente en función de la distancia de movimiento esperado.

Eso es todo IQKeyboardManager hacer por usted con NO línea de código realmente !! Sólo es necesario arrastrar y soltar el archivo de origen Participa en el proyecto. IQKeyboardManager también el apoyo Orientación dispositivo , Gestión UIToolbar Automático , KeybkeyboardDistanceFromTextField y mucho más de lo que cree.

He creado una universales, drop-in UIScrollView, UITableView e incluso subclase UICollectionView que se encarga de mover todos los campos de texto dentro de ella fuera del camino del teclado.

Cuando el teclado está a punto de aparecer, la subclase se encuentra la subvista que está a punto de ser editado, y ajustar su marco y el contenido de desplazamiento para asegurarse de que la vista es visible, con una animación para que coincida con el teclado emergente. Cuando desaparece el teclado, recupera su tamaño anterior.

Se debe trabajar con prácticamente cualquier configuración, ya sea una interfaz basada en UITableView, o uno que consiste en vistas colocado manualmente.

A continuación,' tis: solución para mover los campos de texto de la forma del teclado

  

En Swift Los programadores:

Esto hará todo lo posible para usted, sólo hay que poner estos en su vista de clase del controlador y poner en práctica la UITextFieldDelegate a su controlador de vista y establecer el delegado del textField a self

textField.delegate = self // Setting delegate of your UITextField to self

Implementar los métodos delegado de devolución de llamada:

func textFieldDidBeginEditing(textField: UITextField) {
    animateViewMoving(true, moveValue: 100)
}

func textFieldDidEndEditing(textField: UITextField) {
    animateViewMoving(false, moveValue: 100)
}

// Lifting the view up
func animateViewMoving (up:Bool, moveValue :CGFloat){
    let movementDuration:NSTimeInterval = 0.3
    let movement:CGFloat = ( up ? -moveValue : moveValue)
    UIView.beginAnimations( "animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration )
    self.view.frame = CGRectOffset(self.view.frame, 0,  movement)
    UIView.commitAnimations()
}

Para Swift 4, 4,2, 5: Cambiar

self.view.frame = CGRectOffset(self.view.frame, 0,  movement)

a

self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)

Última nota sobre esta implementación: Si se pulsa otro controlador de vista en la pila mientras se muestra el teclado, esto creará un error donde la vista se devuelve de nuevo a su bastidor central pero el teclado de desplazamiento no se restablece. Por ejemplo, el teclado es el primer nivel de respuesta para nameField, pero luego apretar un botón que empuja a su Help View Controller en su pila. Para solucionar el error de desplazamiento, asegúrese de llamar nameField.resignFirstResponder () antes de salir del controlador de vista, lo que garantiza que el método textFieldDidEndEditing delegado se llama así. Lo hago en el método viewWillDisappear.

Ya hay un montón de respuestas, pero todavía ninguna de las soluciones anteriores habían todas las cosas de fantasía posicionamiento requerido para una animación de "perfecta" libre de errores, compatible hacia atrás y sin parpadeos. (Bug cuando se animan marco / límites y contentOffset juntos, diferentes orientaciones de interfaz, protectores de teclado dividido, ...)
Permítanme compartir mi solución:
(Suponiendo que haya configurado UIKeyboardWill(Show|Hide)Notification)

// Called when UIKeyboardWillShowNotification is sent
- (void)keyboardWillShow:(NSNotification*)notification
{
    // if we have no view or are not visible in any window, we don't care
    if (!self.isViewLoaded || !self.view.window) {
        return;
    }

    NSDictionary *userInfo = [notification userInfo];

    CGRect keyboardFrameInWindow;
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrameInWindow];

    // the keyboard frame is specified in window-level coordinates. this calculates the frame as if it were a subview of our view, making it a sibling of the scroll view
    CGRect keyboardFrameInView = [self.view convertRect:keyboardFrameInWindow fromView:nil];

    CGRect scrollViewKeyboardIntersection = CGRectIntersection(_scrollView.frame, keyboardFrameInView);
    UIEdgeInsets newContentInsets = UIEdgeInsetsMake(0, 0, scrollViewKeyboardIntersection.size.height, 0);

    // this is an old animation method, but the only one that retains compaitiblity between parameters (duration, curve) and the values contained in the userInfo-Dictionary.
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];

    _scrollView.contentInset = newContentInsets;
    _scrollView.scrollIndicatorInsets = newContentInsets;

    /*
     * Depending on visual layout, _focusedControl should either be the input field (UITextField,..) or another element
     * that should be visible, e.g. a purchase button below an amount text field
     * it makes sense to set _focusedControl in delegates like -textFieldShouldBeginEditing: if you have multiple input fields
     */
    if (_focusedControl) {
        CGRect controlFrameInScrollView = [_scrollView convertRect:_focusedControl.bounds fromView:_focusedControl]; // if the control is a deep in the hierarchy below the scroll view, this will calculate the frame as if it were a direct subview
        controlFrameInScrollView = CGRectInset(controlFrameInScrollView, 0, -10); // replace 10 with any nice visual offset between control and keyboard or control and top of the scroll view.

        CGFloat controlVisualOffsetToTopOfScrollview = controlFrameInScrollView.origin.y - _scrollView.contentOffset.y;
        CGFloat controlVisualBottom = controlVisualOffsetToTopOfScrollview + controlFrameInScrollView.size.height;

        // this is the visible part of the scroll view that is not hidden by the keyboard
        CGFloat scrollViewVisibleHeight = _scrollView.frame.size.height - scrollViewKeyboardIntersection.size.height;

        if (controlVisualBottom > scrollViewVisibleHeight) { // check if the keyboard will hide the control in question
            // scroll up until the control is in place
            CGPoint newContentOffset = _scrollView.contentOffset;
            newContentOffset.y += (controlVisualBottom - scrollViewVisibleHeight);

            // make sure we don't set an impossible offset caused by the "nice visual offset"
            // if a control is at the bottom of the scroll view, it will end up just above the keyboard to eliminate scrolling inconsistencies
            newContentOffset.y = MIN(newContentOffset.y, _scrollView.contentSize.height - scrollViewVisibleHeight);

            [_scrollView setContentOffset:newContentOffset animated:NO]; // animated:NO because we have created our own animation context around this code
        } else if (controlFrameInScrollView.origin.y < _scrollView.contentOffset.y) {
            // if the control is not fully visible, make it so (useful if the user taps on a partially visible input field
            CGPoint newContentOffset = _scrollView.contentOffset;
            newContentOffset.y = controlFrameInScrollView.origin.y;

            [_scrollView setContentOffset:newContentOffset animated:NO]; // animated:NO because we have created our own animation context around this code
        }
    }

    [UIView commitAnimations];
}


// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillHide:(NSNotification*)notification
{
    // if we have no view or are not visible in any window, we don't care
    if (!self.isViewLoaded || !self.view.window) {
        return;
    }

    NSDictionary *userInfo = notification.userInfo;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[[userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[[userInfo valueForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];

    // undo all that keyboardWillShow-magic
    // the scroll view will adjust its contentOffset apropriately
    _scrollView.contentInset = UIEdgeInsetsZero;
    _scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;

    [UIView commitAnimations];
}

Shiun dijo "Al final resultó que, creo que la realidad UIScrollView implícitamente trae la UITextField editado en ese momento en la ventana visible de forma implícita" Esto parece ser cierto para IOS 3.1.3, pero no 3.2, 4.0 o 4.1. He tenido que añadir un scrollRectToVisible explícita con el fin de hacer que el UITextField visible en iOS> = 3.2.

Este detalles del documento una solución a este problema. Mirar el código fuente bajo 'movimiento de los contenidos que se encuentra debajo del teclado'. Es bastante sencillo.

EDIT: di cuenta de hay un problema técnico wee en el ejemplo. Es probable que desee para escuchar UIKeyboardWillHideNotification en lugar de UIKeyboardDidHideNotification. De lo contrario la vista de desplazamiento detrás del teclado será recortada por la duración de la animación de cierre teclado.

Una cosa a considerar es si alguna vez desea utilizar un UITextField por su propia cuenta. No he encontrado ninguna de las aplicaciones de iPhone bien diseñados que realmente utilizan UITextFields fuera del UITableViewCells.

Será un trabajo extra, pero recomiendo que implemente todos los datos de entrada MODELOS A las vistas de tabla. Añadir un UITextView a su UITableViewCells.

solución más fácil encontrar

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    const int movementDistance = 80; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed

    int movement = (up ? -movementDistance : movementDistance);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

Poco solución que funcione para muchos UITextFields

#pragma mark UIKeyboard handling

#define kMin 150

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
   if (currTextField) {
      [currTextField release];
   }
   currTextField = [sender retain];
   //move the main view, so that the keyboard does not hide it.
   if (self.view.frame.origin.y + currTextField.frame.origin. y >= kMin) {
        [self setViewMovedUp:YES]; 
   }
}



//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
   [UIView beginAnimations:nil context:NULL];
   [UIView setAnimationDuration:0.3]; // if you want to slide up the view

   CGRect rect = self.view.frame;
   if (movedUp)
   {
      // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
      // 2. increase the size of the view so that the area behind the keyboard is covered up.
      rect.origin.y = kMin - currTextField.frame.origin.y ;
   }
   else
   {
      // revert back to the normal state.
      rect.origin.y = 0;
   }
   self.view.frame = rect;

   [UIView commitAnimations];
}


- (void)keyboardWillShow:(NSNotification *)notif
{
   //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately

   if ([currTextField isFirstResponder] && currTextField.frame.origin.y + self.view.frame.origin.y >= kMin)
   {
      [self setViewMovedUp:YES];
   }
   else if (![currTextField isFirstResponder] && currTextField.frame.origin.y  + self.view.frame.origin.y < kMin)
   {
      [self setViewMovedUp:NO];
   }
}

- (void)keyboardWillHide:(NSNotification *)notif
{
   //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately
   if (self.view.frame.origin.y < 0 ) {
      [self setViewMovedUp:NO];
   }

}


- (void)viewWillAppear:(BOOL)animated
{
   // register for keyboard notifications
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) 
                                                name:UIKeyboardWillShowNotification object:self.view.window]; 
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) 
                                                name:UIKeyboardWillHideNotification object:self.view.window]; 
}

- (void)viewWillDisappear:(BOOL)animated
{
   // unregister for keyboard notifications while not visible.
   [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; 
}

Código de RPDP mueve con éxito el campo de texto de la forma del teclado. Pero cuando se desplaza a la parte superior después de usar y despedir el teclado, la parte superior se ha desplazado hacia arriba fuera de la vista. Esto es cierto para el simulador y el dispositivo. Para leer el contenido en la parte superior de ese punto de vista, hay que recargar la vista.

No se supone que el siguiente código para llevar la vista hacia abajo?

else
{
    // revert back to the normal state.
    rect.origin.y += kOFFSET_FOR_KEYBOARD;
    rect.size.height -= kOFFSET_FOR_KEYBOARD;
}

No estoy seguro de si se mueve la vista hacia arriba es el enfoque correcto, lo hice de una manera differente, cambiar el tamaño de la UIScrollView. Se lo expliqué en detalles sobre un artículo rel="noreferrer"> href="http://www.iphonesampleapps.com/2009/12/adjust-uitextfield-hidden-behind-keyboard-with-uiscrollview/" poco

Para traer de vuelta al estado de vista original, añadir:

-(void)textFieldDidEndEditing:(UITextField *)sender

{
    //move the main view, so that the keyboard does not hide it.
    if  (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

Trate de este breve truco.

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    const int movementDistance = textField.frame.origin.y / 2; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed

    int movement = (up ? -movementDistance : movementDistance);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

Hay muchas soluciones, pero no tengo pasar algunas horas antes de que comience las obras. Por lo tanto, pongo este código aquí (Sólo tienes que pegar al proyecto, las modificaciones no necesitan):

@interface RegistrationViewController : UIViewController <UITextFieldDelegate>{
    UITextField* activeField;
    UIScrollView *scrollView;
}
@end

- (void)viewDidLoad
{
    [super viewDidLoad];

    scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];

    //scrool view must be under main view - swap it
    UIView* natView = self.view;
    [self setView:scrollView];
    [self.view addSubview:natView];

    CGSize scrollViewContentSize = self.view.frame.size;
    [scrollView setContentSize:scrollViewContentSize];

    [self registerForKeyboardNotifications];
}

- (void)viewDidUnload {
    activeField = nil;
    scrollView = nil;
    [self unregisterForKeyboardNotifications];
    [super viewDidUnload];
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];

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

}

-(void)unregisterForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}

- (void)keyboardWillShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGRect frame = self.view.frame;
    frame.size.height -= kbSize.height;
    CGPoint fOrigin = activeField.frame.origin;
    fOrigin.y -= scrollView.contentOffset.y;
    fOrigin.y += activeField.frame.size.height;
    if (!CGRectContainsPoint(frame, fOrigin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y + activeField.frame.size.height - frame.size.height);
        [scrollView setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
     [scrollView setContentOffset:CGPointZero animated:YES];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    activeField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    activeField = nil;
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

P.S: espero que el código de ayuda a alguien a hacer efecto deseado de forma rápida. (Xcode 4.5)

@ user271753

Para obtener su vista hacia atrás para agregar el original:

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
   [textField resignFirstResponder];
   [self setViewMovedUp:NO];
   return YES;
}

Swift 4 .

usted puede fácilmente moverse hacia arriba y hacia abajo o UITextField UIView Con UIKeyBoard Con Animation introducir descripción de la imagen aquí

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textField: UITextField!
    @IBOutlet var chatView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillChangeFrame, object: nil)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textField.resignFirstResponder()
    }

    @objc func keyboardWillChange(notification: NSNotification) {

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y
        print("deltaY",deltaY)

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.chatView.frame.origin.y+=deltaY // Here You Can Change UIView To UITextField
        },completion: nil)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

}

Aquí está la solución truco que se me ocurrió para un diseño específico. Esta solución es similar a la solución Matt Gallagher en que es se desplaza una sección a la vista. Todavía soy nuevo en el desarrollo iPhone, y no estoy familiarizado con el funcionamiento de los diseños. Por lo tanto, este corte.

Mi aplicación necesaria para soportar el desplazamiento cuando se hace clic en un campo, y también el desplazamiento cuando el usuario selecciona el siguiente en el teclado.

Yo tenía un UIView con una altura de 775. Los controles se extienden básicamente en grupos de 3 en un gran espacio. Terminé con la siguiente distribución del IB.

UIView -> UIScrollView -> [UI Components]

A continuación viene el truco

I establecer la altura UIScrollView a 500 unidades más grandes entonces la disposición real (1250). Entonces creó una matriz con las posiciones absolutas que tenga que desplazarse a, y una función sencilla de conseguir que se basan en el número de etiqueta de IB.

static NSInteger stepRange[] = {
    0, 0, 0, 0, 0, 0, 0, 0, 0, 140, 140, 140, 140, 140, 410
};

NSInteger getScrollPos(NSInteger i) {
    if (i < TXT_FIELD_INDEX_MIN || i > TXT_FIELD_INDEX_MAX) {
        return 0 ;
    return stepRange[i] ;
}

Ahora todo lo que necesita hacer es usar las siguientes dos líneas de código en textFieldDidBeginEditing y textFieldShouldReturn (este último uno si va a crear un campo al lado de navegación)

CGPoint point = CGPointMake(0, getScrollPos(textField.tag)) ;
[self.scrollView setContentOffset:point animated:YES] ;

Un ejemplo.

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    CGPoint point = CGPointMake(0, getScrollPos(textField.tag)) ;
    [self.scrollView setContentOffset:point animated:YES] ;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    NSInteger nextTag = textField.tag + 1;
    UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];

    if (nextResponder) {
        [nextResponder becomeFirstResponder];
        CGPoint point = CGPointMake(0, getScrollPos(nextTag)) ;
        [self.scrollView setContentOffset:point animated:YES] ;
    }
    else{
        [textField resignFirstResponder];
    }

    return YES ;
}

Este método no 'desplazarse hacia atrás', como lo hacen otros métodos. Esto no era un requisito. De nuevo, esto era bastante para un UIView 'alto', y yo no tenía días para aprender los motores de diseño internos.

Como por los documentos , a partir de iOS 3.0, la clase UITableViewController redimensiona y coloca su vista de tabla cuando hay edición en línea de los campos de texto de forma automática. Creo que no es suficiente para poner el campo de texto dentro de un UITableViewCell como algunos han indicado.

Desde los documentos :

  

Un controlador de vista de tabla soporta la edición en línea de la vista tabla filas;   campos de texto si, por ejemplo, las filas se han incrustado en el modo de edición, se   volutas está editando la fila superior del teclado virtual que es   visualizada.

  

Aquí He encontrado la solución más simple para manejar el teclado.

Es necesario simplemente copiar y pegar código de ejemplo a continuación y cambiar su campo de texto o cualquier punto de vista que desea mover hacia arriba.

Paso-1

  

Sólo tienes que copiar y pegar a continuación dos métodos en su controlador

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

- (void)deregisterFromKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

Paso-2

  

registrar y dar de baja del teclado Notificaciones en viewWillAppear y    viewWillDisappear métodos respectivamente.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self registerForKeyboardNotifications];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self deregisterFromKeyboardNotifications];
    [super viewWillDisappear:animated];
}

Paso 3

  

A continuación viene la parte del alma, Basta con sustituir el campo de texto, y el cambio   altura de la cantidad que desea mover al revés.

- (void)keyboardWasShown:(NSNotification *)notification
{
    NSDictionary* info = [notification userInfo];
    CGSize currentKeyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    //you need replace your textfield instance here
    CGPoint textFieldOrigin = self.tokenForPlaceField.frame.origin;
    CGFloat textFieldHeight = self.tokenForPlaceField.frame.size.height;

    CGRect visibleRect = self.view.frame;
    visibleRect.size.height -= currentKeyboardSize.height;

    if (!CGRectContainsPoint(visibleRect, textFieldOrigin))
    {
        //you can add yor desired height how much you want move keypad up, by replacing "textFieldHeight" below

        CGPoint scrollPoint = CGPointMake(0.0, textFieldOrigin.y - visibleRect.size.height  + textFieldHeight); //replace textFieldHeight to currentKeyboardSize.height, if you want to move up with more height
        [self.scrollView setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification *)notification
{
    [self.scrollView setContentOffset:CGPointZero animated:YES];
}

referencia : así, Por favor, apreciar este chico , que compartió esta bella sección de código, solución limpia.

Espero que esto sería alguien hosco útiles por ahí.

estado buscando un buen tutorial para principiantes en la materia, que se encuentra el mejor tutorial aquí .

En el ejemplo MIScrollView.h en la parte inferior del tutorial asegúrese de poner un espacio en

@property (nonatomic, retain) id backgroundTapDelegate;

como se ve.

Cuando UITextField está en un desplazamiento UITableViewCell debe ser configurado de forma automática.

Si no lo es, es probablemente debido a un código incorrecto / configuración de la tableview.

Por ejemplo, cuando volví a cargar mi larga mesa con una UITextField en la parte inferior de la siguiente manera:

-(void) viewWillAppear:(BOOL)animated
{
   [self.tableview reloadData];
}

entonces mi campo de texto en la parte inferior fue oscurecido por el teclado que aparece cuando hace clic dentro del campo de texto.

Para solucionar este problema que tenía que hacer esto -

-(void) viewWillAppear:(BOOL)animated
{
    //add the following line to fix issue
    [super viewWillAppear:animated];
    [self.tableview reloadData];
}

Utilice esta tercera parte que no es necesario escribir ni una línea

https://github.com/hackiftekhar/IQKeyboardManager

Proyectos descarga y arrastrar y soltar IQKeyboardManager en su proyecto. Si encuentra algún problema por favor lea el documento README.

Los chicos realmente su dolor de cabeza remove para manejar el teclado ..

Gracias y mucha suerte!

Nota: : esta respuesta supone que su textField está en una ScrollView

.

Prefiero tratar con esta usando scrollContentInset y scrollContentOffset en lugar de jugar con los marcos de mi punto de vista.

En primer lugar vamos a escuchar a las notificaciones de teclado

//call this from viewWillAppear
-(void)addKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
//call this from viewWillDisappear
-(void)removeKeyboardNotifications{
    [[NSNotificationCenter default
    Center] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

El siguiente paso es mantener una propiedad que representa la corriente de primera respuesta (UITextField / UITextView que actualmente tiene el teclado).

Utilizamos los métodos de delegado para establecer esta propiedad. Si está utilizando otro componente, necesitará algo similar.

Tenga en cuenta que para el campo de texto lo ponemos en didBeginEditing y para Textview en shouldBeginEditing. Esto se debe a textViewDidBeginEditing se llamó después UIKeyboardWillShowNotification por alguna razón.

-(BOOL)textViewShouldBeginEditing:(UITextView * )textView{
    self.currentFirstResponder = textView;
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    self.currentFirstResponder = textField;
}

Por último, aquí está la magia

- (void)keyboardWillShow:(NSNotification*)aNotification{
    NSDictionary* info = [aNotification userInfo];
    CGRect kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];


    /*if currentFirstResponder is overlayed by the keyboard, move it so it bottom ends where the keyboard begins*/
    if(self.currentFirstResponder){

        //keyboard origin in currentFirstResponderFrame
        CGPoint keyboardOrigin = [self.currentFirstResponder convertPoint:kbFrame.origin fromView:nil];

        float spaceBetweenFirstResponderAndKeyboard = abs(self.currentFirstResponder.frame.size.height-keyboardOrigin.y);

        //only scroll the scrollview if keyboard overlays the first responder
        if(spaceBetweenFirstResponderAndKeyboard>0){
            //if i call setContentOffset:animate:YES it behaves differently, not sure why
            [UIView animateWithDuration:0.25 animations:^{
                [self.scrollView setContentOffset:CGPointMake(0,self.scrollView.contentOffset.y+spaceBetweenFirstResponderAndKeyboard)];
            }];
        }
    }

    //set bottom inset to the keyboard height so you can still scroll the whole content

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbFrame.size.height, 0.0);
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;

}

- (void)keyboardWillHide:(NSNotification*)aNotification{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
}

Esta es la solución utilizando Swift.

import UIKit

class ExampleViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var scrollView: UIScrollView!

    @IBOutlet var textField1: UITextField!
    @IBOutlet var textField2: UITextField!
    @IBOutlet var textField3: UITextField!
    @IBOutlet var textField4: UITextField!
    @IBOutlet var textField5: UITextField!

    var activeTextField: UITextField!

    // MARK: - View
    override func viewDidLoad() {
        super.viewDidLoad()
        self.textField1.delegate = self
        self.textField2.delegate = self
        self.textField3.delegate = self
        self.textField4.delegate = self
        self.textField5.delegate = self
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.registerForKeyboardNotifications()
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        self.unregisterFromKeyboardNotifications()
    }

    // MARK: - Keyboard

    // Call this method somewhere in your view controller setup code.
    func registerForKeyboardNotifications() {
        let center:  NSNotificationCenter = NSNotificationCenter.defaultCenter()
        center.addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
        center.addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
    }

    func unregisterFromKeyboardNotifications () {
        let center:  NSNotificationCenter = NSNotificationCenter.defaultCenter()
        center.removeObserver(self, name: UIKeyboardDidShowNotification, object: nil)
        center.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
    }

    // Called when the UIKeyboardDidShowNotification is sent.
    func keyboardWasShown (notification: NSNotification) {
        let info : NSDictionary = notification.userInfo!
        let kbSize = (info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue() as CGRect!).size

        let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
        scrollView.contentInset = contentInsets;
        scrollView.scrollIndicatorInsets = contentInsets;

        // If active text field is hidden by keyboard, scroll it so it's visible
        // Your app might not need or want this behavior.
        var aRect = self.view.frame
        aRect.size.height -= kbSize.height;
        if (!CGRectContainsPoint(aRect, self.activeTextField.frame.origin) ) {
            self.scrollView.scrollRectToVisible(self.activeTextField.frame, animated: true)
        }
    }

    // Called when the UIKeyboardWillHideNotification is sent
    func keyboardWillBeHidden (notification: NSNotification) {
        let contentInsets = UIEdgeInsetsZero;
        scrollView.contentInset = contentInsets;
        scrollView.scrollIndicatorInsets = contentInsets;
    }

    // MARK: -  Text Field

    func textFieldDidBeginEditing(textField: UITextField) {
        self.activeTextField = textField
    }

    func textFieldDidEndEditing(textField: UITextField) {
        self.activeTextField = nil
    }

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