Hacer un desplazamiento UITableView cuando se selecciona el campo de texto

votos
228

Después de mucho ensayo y error, me estoy rindiendo y haciendo la pregunta. He visto a muchas personas con problemas similares pero no pueden obtener todas las respuestas para que funcionen bien.

Tengo un UITableViewque está compuesto de células personalizadas. Las celdas están formadas por 5 campos de texto uno al lado del otro (algo así como una grilla).

Cuando intento desplazarme y editar las celdas de la parte inferior de la página UITableView, no logro colocar mis celdas correctamente sobre el teclado.

He visto muchas respuestas sobre el cambio de tamaño de vista, etc. ... pero ninguna de ellas ha funcionado bien hasta ahora.

¿Alguien podría aclarar la forma correcta de hacer esto con un ejemplo de código concreto?

Publicado el 27/02/2009 a las 11:05
fuente por usuario
En otros idiomas...                            


48 respuestas

votos
110

Si utiliza UITableViewController en lugar de UIViewController, lo hará automáticamente de modo.

Respondida el 21/09/2010 a las 04:42
fuente por usuario

votos
89

La función que hace el desplazamiento podría ser mucho más simple:

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    UITableViewCell *cell;

    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
    // Load resources for iOS 6.1 or earlier
        cell = (UITableViewCell *) textField.superview.superview;

    } else {
        // Load resources for iOS 7 or later
        cell = (UITableViewCell *) textField.superview.superview.superview; 
       // TextField -> UITableVieCellContentView -> (in iOS 7!)ScrollView -> Cell!
    }
    [tView scrollToRowAtIndexPath:[tView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

Eso es. Sin cálculos en absoluto.

Respondida el 15/04/2009 a las 13:21
fuente por usuario

votos
65

Estoy haciendo algo muy similar que es genérico, no hay necesidad de calcular algo específico para su código. Sólo tienes que comprobar las observaciones sobre el código:

en MyUIViewController.h

@interface MyUIViewController: UIViewController <UITableViewDelegate, UITableViewDataSource>
{
     UITableView *myTableView;
     UITextField *actifText;
}

@property (nonatomic, retain) IBOutlet UITableView *myTableView;
@property (nonatomic, retain) IBOutlet UITextField *actifText;

- (IBAction)textFieldDidBeginEditing:(UITextField *)textField;
- (IBAction)textFieldDidEndEditing:(UITextField *)textField;

-(void) keyboardWillHide:(NSNotification *)note;
-(void) keyboardWillShow:(NSNotification *)note;

@end

en MyUIViewController.m

@implementation MyUIViewController

@synthesize myTableView;
@synthesize actifText;

- (void)viewDidLoad 
{
    // Register notification when the keyboard will be show
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(keyboardWillShow:)
                                          name:UIKeyboardWillShowNotification
                                          object:nil];

    // Register notification when the keyboard will be hide
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(keyboardWillHide:)
                                          name:UIKeyboardWillHideNotification
                                          object:nil];
}

// To be link with your TextField event "Editing Did Begin"
//  memoryze the current TextField
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    self.actifText = textField;
}

// To be link with your TextField event "Editing Did End"
//  release current TextField
- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    self.actifText = nil;
}

-(void) keyboardWillShow:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

    // Detect orientation
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect frame = self.myTableView.frame;

    // Start animation
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    // Reduce size of the Table view 
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
        frame.size.height -= keyboardBounds.size.height;
    else 
        frame.size.height -= keyboardBounds.size.width;

    // Apply new size of table view
    self.myTableView.frame = frame;

    // Scroll the table view to see the TextField just above the keyboard
    if (self.actifText)
      {
        CGRect textFieldRect = [self.myTableView convertRect:self.actifText.bounds fromView:self.actifText];
        [self.myTableView scrollRectToVisible:textFieldRect animated:NO];
      }

    [UIView commitAnimations];
}

-(void) keyboardWillHide:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

    // Detect orientation
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect frame = self.myTableView.frame;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    // Increase size of the Table view 
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
        frame.size.height += keyboardBounds.size.height;
    else 
        frame.size.height += keyboardBounds.size.width;

    // Apply new size of table view
    self.myTableView.frame = frame;

    [UIView commitAnimations];
}

@end

Swift versión 1.2+:

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var activeText: UITextField!
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: Selector("keyboardWillShow:"),
            name: UIKeyboardWillShowNotification,
            object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: Selector("keyboardWillHide:"),
            name: UIKeyboardWillHideNotification,
            object: nil)
    }

    func textFieldDidBeginEditing(textField: UITextField) {
        activeText = textField
    }

    func textFieldDidEndEditing(textField: UITextField) {
        activeText = nil
    }

    func keyboardWillShow(note: NSNotification) {
        if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            var frame = tableView.frame
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationBeginsFromCurrentState(true)
            UIView.setAnimationDuration(0.3)
            frame.size.height -= keyboardSize.height
            tableView.frame = frame
            if activeText != nil {
                let rect = tableView.convertRect(activeText.bounds, fromView: activeText)
                tableView.scrollRectToVisible(rect, animated: false)
            }
            UIView.commitAnimations()
        }
    }

    func keyboardWillHide(note: NSNotification) {
        if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            var frame = tableView.frame
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationBeginsFromCurrentState(true)
            UIView.setAnimationDuration(0.3)
            frame.size.height += keyboardSize.height
            tableView.frame = frame
            UIView.commitAnimations()
        }
    }
}
Respondida el 13/04/2010 a las 15:46
fuente por usuario

votos
41

Yo tenía el mismo problema, pero di cuenta de que sólo aparezca en una vista. Así que empecé a buscar las diferencias en los controladores.

He encontrado que el comportamiento de desplazamiento se define en el - (void)viewWillAppear:(BOOL)animatedde la instancia súper.

Así que asegúrese de aplicar la siguiente manera:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // your code
}

Y no importa si utiliza UIViewControllero UITableViewController; comprobado por poner un UITableViewcomo un subvista de self.view en el UIViewController. Fue el mismo comportamiento. La vista no permitió que desplazarse si la llamada [super viewWillAppear:animated];había desaparecido.

Respondida el 29/05/2011 a las 01:42
fuente por usuario

votos
37

me hayan pasado esto, ya que no he leído todo el post aquí, pero lo que ocurrió con parece engañosamente simple. No he puesto esto a través del escurridor, poniendo a prueba en todas las situaciones, pero parece que debería funcionar bien.

sólo tiene que ajustar el contentInset del tableview por la altura del teclado, y luego desplazarse a la celda a la parte inferior:

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

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    self.myTableView.contentInset = contentInsets;
    self.myTableView.scrollIndicatorInsets = contentInsets;

    [self.myTableView scrollToRowAtIndexPath:self.currentField.indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

y por supuesto

- (void)keyboardWasHidden:(NSNotification *)aNotification
{
    [UIView animateWithDuration:.3 animations:^(void) 
    {
        self.myTableView.contentInset = UIEdgeInsetsZero;
        self.myTableView.scrollIndicatorInsets = UIEdgeInsetsZero;
    }];
}

Es esta demasiado simple? ¿Me estoy perdiendo de algo? hasta el momento se está trabajando bien para mí, pero como ya he dicho, no he puesto que a través del escurridor ...

Respondida el 18/08/2012 a las 01:12
fuente por usuario

votos
35

La solución más sencilla para Swift 3 , basado en la solución Bartłomiej Semańczyk :

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(CreateEditRitualViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(CreateEditRitualViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

// MARK: Keyboard Notifications

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardHeight = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height {
        tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.2, animations: {
        // For some reason adding inset in keyboardWillShow is animated by itself but removing is not, that's why we have to use animateWithDuration here
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
    })
}
Respondida el 08/12/2016 a las 10:26
fuente por usuario

votos
34

Si puede utilizar UITableViewController, se obtiene la funcionalidad de forma gratuita. A veces, sin embargo, esto no es una opción, especialmente si necesita varios puntos de vista no sólo el UITableView.

Algunas de las soluciones que se presentan aquí no funcionan en iOS ≥4, algunos no funcionan en el iPad o en modo paisaje, algunos no funcionan para teclados Bluetooth (donde no queremos ningún desplazamiento), algunos no lo hacen trabajar cuando se cambia entre varios campos de texto. Así que si usted elige cualquier solución, asegúrese de probar estos casos. Esta es la solución que utilizamos utilizamos en InAppSettingsKit :

- (void)_keyboardWillShow:(NSNotification*)notification {
    if (self.navigationController.topViewController == self) {
        NSDictionary* userInfo = [notification userInfo];

        // we don't use SDK constants here to be universally compatible with all SDKs ≥ 3.0
        NSValue* keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"];
        if (!keyboardFrameValue) {
            keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
        }

        // Reduce the tableView height by the part of the keyboard that actually covers the tableView
        CGRect windowRect = [[UIApplication sharedApplication] keyWindow].bounds;
        if (UIInterfaceOrientationLandscapeLeft == self.interfaceOrientation ||UIInterfaceOrientationLandscapeRight == self.interfaceOrientation ) {
            windowRect = IASKCGRectSwap(windowRect);
        }
        CGRect viewRectAbsolute = [_tableView convertRect:_tableView.bounds toView:[[UIApplication sharedApplication] keyWindow]];
        if (UIInterfaceOrientationLandscapeLeft == self.interfaceOrientation ||UIInterfaceOrientationLandscapeRight == self.interfaceOrientation ) {
            viewRectAbsolute = IASKCGRectSwap(viewRectAbsolute);
        }
        CGRect frame = _tableView.frame;
        frame.size.height -= [keyboardFrameValue CGRectValue].size.height - CGRectGetMaxY(windowRect) + CGRectGetMaxY(viewRectAbsolute);

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
        [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
        _tableView.frame = frame;
        [UIView commitAnimations];

        UITableViewCell *textFieldCell = (id)((UITextField *)self.currentFirstResponder).superview.superview;
        NSIndexPath *textFieldIndexPath = [_tableView indexPathForCell:textFieldCell];

        // iOS 3 sends hide and show notifications right after each other
        // when switching between textFields, so cancel -scrollToOldPosition requests
        [NSObject cancelPreviousPerformRequestsWithTarget:self];

        [_tableView scrollToRowAtIndexPath:textFieldIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
}

- (void) scrollToOldPosition {
  [_tableView scrollToRowAtIndexPath:_topmostRowBeforeKeyboardWasShown atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)_keyboardWillHide:(NSNotification*)notification {
    if (self.navigationController.topViewController == self) {
        NSDictionary* userInfo = [notification userInfo];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
        [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
        _tableView.frame = self.view.bounds;
        [UIView commitAnimations];

        [self performSelector:@selector(scrollToOldPosition) withObject:nil afterDelay:0.1];
    }
}   

Aquí está el código completo de la clase en InAppSettingsKit. Para probarlo, utilice el panel de niño "Lista completa de" donde se pueden probar los escenarios mencionados anteriormente.

Respondida el 13/12/2010 a las 17:01
fuente por usuario

votos
34

Creo que he encontrado la solución para que coincida con el comportamiento de las aplicaciones de Apple.

Primero, en su vista aparecerá: suscríbase a las notificaciones del teclado, para saber cuándo se mostrará y se ocultará el teclado, y el sistema le dirá el tamaño del teclado, pero no se olvide de cancelar el registro en su vista. Desaparecerá :.

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

Implemente los métodos similares a los de abajo para que ajuste el tamaño de su tableView para que coincida con el área visible una vez que se muestra el teclado. Aquí estoy rastreando el estado del teclado por separado para que pueda elegir cuándo establecer la vista de mesa en altura completa, ya que recibe estas notificaciones en cada cambio de campo. No se olvide de implementar keyboardWillHide: y elija un lugar apropiado para arreglar su tamaño de tableView.

-(void) keyboardWillShow:(NSNotification *)note
{
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
    keyboardHeight = keyboardBounds.size.height;
    if (keyboardIsShowing == NO)
    {
        keyboardIsShowing = YES;
        CGRect frame = self.view.frame;
        frame.size.height -= keyboardHeight;

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.3f];
        self.view.frame = frame;
        [UIView commitAnimations];
    }
}

Ahora esta es la barra de desplazamiento, primero trabajamos en algunos tamaños, luego vemos dónde estamos en el área visible y establecemos el rect que queremos que sea la mitad de arriba o abajo del medio del campo de texto en donde está en la vista. En este caso, tenemos una matriz de UITextFields y una enumeración que realiza un seguimiento de ellos, por lo que multiplicar rowHeight por el número de fila nos da el desplazamiento real del marco dentro de esta vista externa.

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    CGFloat rowHeight = self.tableView.rowHeight;
    if (textField == textFields[CELL_FIELD_ONE])
    {
        frame.origin.y += rowHeight * CELL_FIELD_ONE;
    }
    else if (textField == textFields[CELL_FIELD_TWO])
    {
        frame.origin.y += rowHeight * CELL_FIELD_TWO;
    }
    else if (textField == textFields[CELL_FIELD_THREE])
    {
        frame.origin.y += rowHeight * CELL_FIELD_THREE;
    }
    else if (textField == textFields[CELL_FIELD_FOUR])
    {
        frame.origin.y += rowHeight * CELL_FIELD_FOUR;
    }
    CGFloat viewHeight = self.tableView.frame.size.height;
    CGFloat halfHeight = viewHeight / 2;
    CGFloat midpoint = frame.origin.y + (textField.frame.size.height / 2);
    if (midpoint < halfHeight)
    {
        frame.origin.y = 0;
        frame.size.height = midpoint;
    }
    else
    {
        frame.origin.y = midpoint;
        frame.size.height = midpoint;
    }
    [self.tableView scrollRectToVisible:frame animated:YES];
}

Esto parece funcionar bastante bien.

Respondida el 23/03/2009 a las 02:49
fuente por usuario

votos
22

La solución más sencilla para Swift :

override func viewDidLoad() {
    super.viewDidLoad()

    searchBar?.becomeFirstResponder()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.keyboardWillShow(_:)), name: UIKeyboardDidShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.keyboardWillHide(_:)), name: UIKeyboardDidHideNotification, object: nil)
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue.size.height {
            tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    UIView.animateWithDuration(0.2, animations: { self.table_create_issue.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) })
    // For some reason adding inset in keyboardWillShow is animated by itself but removing is not, that's why we have to use animateWithDuration here
    }
Respondida el 25/08/2015 a las 06:42
fuente por usuario

votos
6

Espero que ustedes ya tiene una solución de leer todos aquellos. Pero encontré mi solución de la siguiente manera. Estoy esperando que usted ya tiene una celda con UITextField. Así que en la preparación de simplemente mantener el índice de fila en la etiqueta del campo de texto.

cell.textField.tag = IndexPath.row;

Crear una activeTextField, instancia de UITextFieldámbito global de la siguiente manera:

@interface EditViewController (){

    UITextField *activeTextField;

}

Así que, ahora que acaba de copiar y pegar el código en el final. Y también no se olvide de añadirUITextFieldDelegate

#pragma mark - TextField Delegation

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

    activeTextField = textField;

    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{

    activeTextField = nil;

}

teclado registros notifications

#pragma mark - Keyboard Activity

- (void)registerForKeyboardNotifications

{

    [[NSNotificationCenter defaultCenter] addObserver:self

                                         selector:@selector(keyboardWasShown:)

                                             name:UIKeyboardDidShowNotification object:nil];



    [[NSNotificationCenter defaultCenter] addObserver:self

                                         selector:@selector(keyboardWillBeHidden:)

                                             name:UIKeyboardWillHideNotification object:nil];



}

Maneja el teclado Notifications:

Se llama cuando el UIKeyboardDidShowNotificationse envía.

- (void)keyboardWasShown:(NSNotification*)aNotification

{

    NSDictionary* info = [aNotification userInfo];

    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);

    [self.tableView setContentInset:contentInsets];

    [self.tableView setScrollIndicatorInsets:contentInsets];

    NSIndexPath *currentRowIndex = [NSIndexPath indexPathForRow:activeTextField.tag inSection:0];

    [self.tableView scrollToRowAtIndexPath:currentRowIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];

}

Llama cuando el UIKeyboardWillHideNotificationse envía

- (void)keyboardWillBeHidden:(NSNotification*)aNotification

{

    UIEdgeInsets contentInsets = UIEdgeInsetsZero;

    [self.tableView setContentInset:contentInsets];

    [self.tableView setScrollIndicatorInsets:contentInsets];

}

Ahora, una cosa es la izquierda, llamar al registerForKeyboardNotificationsmétodo en el que ViewDidLoadel método de la siguiente manera:

- (void)viewDidLoad {

    [super viewDidLoad];

    // Registering keyboard notification

    [self registerForKeyboardNotifications];

    // Your codes here...

}

Usted está hecho, espera que su textFieldsvoluntad ya no se oculta por el teclado.

Respondida el 03/01/2015 a las 21:36
fuente por usuario

votos
6

La combinación y llenar los espacios en blanco de varias respuestas (en particular Ortwin Gentz, el usuario 98013) y otro puesto, esto va a funcionar fuera de la caja para SDK 4.3 en un iPad en modo retrato o paisaje:

@implementation UIView (FindFirstResponder)
- (UIResponder *)findFirstResponder
{
  if (self.isFirstResponder) {        
    return self;     
  }

  for (UIView *subView in self.subviews) {
    UIResponder *firstResponder = [subView findFirstResponder];
    if (firstResponder != nil) {
      return firstResponder;
    }
  }

  return nil;
}
@end

@implementation MyViewController

- (UIResponder *)currentFirstResponder {
  return [self.view findFirstResponder];
}

- (IBAction)editingEnded:sender {
  [sender resignFirstResponder];
}

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

- (void)textFieldDidBeginEditing:(UITextField *)textField {
  UITableViewCell *cell = (UITableViewCell*) [[textField superview] superview];
  [_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)keyboardWillShow:(NSNotification*)notification {
  if ([self currentFirstResponder] != nil) {
    NSDictionary* userInfo = [notification userInfo];

    // we don't use SDK constants here to be universally compatible with all SDKs ≥ 3.0
    NSValue* keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"];
    if (!keyboardFrameValue) {
      keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
    }

    // Reduce the tableView height by the part of the keyboard that actually covers the tableView
    CGRect windowRect = [[UIApplication sharedApplication] keyWindow].bounds;
    CGRect viewRectAbsolute = [_tableView convertRect:_tableView.bounds toView:[[UIApplication sharedApplication] keyWindow]];
    CGRect frame = _tableView.frame;
    if (UIInterfaceOrientationLandscapeLeft == self.interfaceOrientation ||UIInterfaceOrientationLandscapeRight == self.interfaceOrientation ) {
      windowRect = CGRectMake(windowRect.origin.y, windowRect.origin.x, windowRect.size.height, windowRect.size.width);
      viewRectAbsolute = CGRectMake(viewRectAbsolute.origin.y, viewRectAbsolute.origin.x, viewRectAbsolute.size.height, viewRectAbsolute.size.width);
    }
    frame.size.height -= [keyboardFrameValue CGRectValue].size.height - CGRectGetMaxY(windowRect) + CGRectGetMaxY(viewRectAbsolute);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
    _tableView.frame = frame;
    [UIView commitAnimations];

    UITableViewCell *textFieldCell = (id)((UITextField *)self.currentFirstResponder).superview.superview;
    NSIndexPath *textFieldIndexPath = [_tableView indexPathForCell:textFieldCell];

    // iOS 3 sends hide and show notifications right after each other
    // when switching between textFields, so cancel -scrollToOldPosition requests
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    _topmostRowBeforeKeyboardWasShown = [[_tableView indexPathsForVisibleRows] objectAtIndex:0];
    [_tableView scrollToRowAtIndexPath:textFieldIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
  }
}

- (void) scrollToOldPosition {
  [_tableView scrollToRowAtIndexPath:_topmostRowBeforeKeyboardWasShown atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)keyboardWillHide:(NSNotification*)notification {
  if ([self currentFirstResponder] != nil) {

    NSDictionary* userInfo = [notification userInfo];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
    _tableView.frame = self.view.bounds;
    [UIView commitAnimations];

    [self performSelector:@selector(scrollToOldPosition) withObject:nil afterDelay:0.1];
  }
}   

@end
Respondida el 03/08/2011 a las 03:35
fuente por usuario

votos
5

Mi acercamiento:

La primera subclase UITextField y añadir una propiedad indexPath. En el Cellfor ... Método de ceder la propiedad indexPath.

Luego añadir siguiente código:

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:textField.indexPath];

CGPoint cellPoint = [cell convertPoint:textField.center toView:self.tableView];
[UIView animateWithDuration:0.3 animations:^(void){self.tableView.contentOffset = CGPointMake(0, cellPoint.y-50);}];

a la textFieldShould / WillBegin ... etc.

Cuando el teclado desaparece usted tiene que invertir con:

[UIView animateWithDuration:0.3 animations:^(void){self.tableView.contentOffset = CGPointMake(0, 0);}];
Respondida el 29/09/2012 a las 13:03
fuente por usuario

votos
4

Utilice UITextField's delegateel método:

Rápido

func textFieldShouldBeginEditing(textField: UITextField) -> bool {
  let txtFieldPosition = textField.convertPoint(textField.bounds.origin, toView: yourTableViewHere)
  let indexPath = yourTablViewHere.indexPathForRowAtPoint(txtFieldPosition)
  if indexPath != nil {
     yourTablViewHere.scrollToRowAtIndexPath(indexPath!, atScrollPosition: .Top, animated: true)
  }
  return true
}

C objetivo

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
  CGPoint txtFieldPosition = [textField convertPoint:CGPointZero toView: yourTablViewHere];
  NSLog(@"Begin txtFieldPosition : %@",NSStringFromCGPoint(txtFieldPosition));
  NSIndexPath *indexPath = [yourTablViewHere indexPathForRowAtPoint:txtFieldPosition];

  if (indexPath != nil) {
     [yourTablViewHere scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
  }
  return YES;
}
Respondida el 20/03/2015 a las 07:00
fuente por usuario

votos
4

La respuesta correcta es la respuesta de Sam Ho:

"Si utiliza UITableViewController en lugar de UIViewController, lo hará automáticamente de modo.".

Sólo asegúrese de conectar su UITableView a la propiedad de la TableView UITableViewController (por ejemplo, por lo que no lo agregue como una vista secundaria de la propiedad Vista de la UITableViewController).

Asimismo, asegúrese de establecer la propiedad AutoresizingMask de su UITableView a FlexibleHeight

Respondida el 09/12/2010 a las 11:28
fuente por usuario

votos
4

Si se utiliza Three20, a continuación, utilizar la autoresizesForKeyboardpropiedad. Sólo hay que establecer en el controlador de vista de su -initWithNibName:bundlemétodo

self.autoresizesForKeyboard = YES

Este se encarga de:

  1. La escucha de notificaciones de teclado y ajustar el marco de la vista de tabla
  2. Desplazándose hasta el primer nivel de respuesta

Hecho y hecho.

Respondida el 21/09/2010 a las 14:19
fuente por usuario

votos
4

Las notificaciones de teclado funcionan, pero el código de muestra de Apple para eso asume que la vista de desplazamiento es la vista raíz de la ventana. Usualmente este no es el caso. Debe compensar las barras de pestañas, etc. para obtener el desplazamiento correcto.

Es más fácil de lo que parece. Aquí está el código que uso en UITableViewController. Tiene dos variables de instancia, hiddenRect y keyboardShown.

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification {
    if (keyboardShown)
        return;

    NSDictionary* info = [aNotification userInfo];

    // Get the frame of the keyboard.
    NSValue *centerValue = [info objectForKey:UIKeyboardCenterEndUserInfoKey];
    NSValue *boundsValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    CGPoint keyboardCenter = [centerValue CGPointValue];
    CGRect keyboardBounds = [boundsValue CGRectValue];
    CGPoint keyboardOrigin = CGPointMake(keyboardCenter.x - keyboardBounds.size.width / 2.0,
                                         keyboardCenter.y - keyboardBounds.size.height / 2.0);
    CGRect keyboardScreenFrame = { keyboardOrigin, keyboardBounds.size };


    // Resize the scroll view.
    UIScrollView *scrollView = (UIScrollView *) self.tableView;
    CGRect viewFrame = scrollView.frame;
    CGRect keyboardFrame = [scrollView.superview convertRect:keyboardScreenFrame fromView:nil];
    hiddenRect = CGRectIntersection(viewFrame, keyboardFrame);

    CGRect remainder, slice;
    CGRectDivide(viewFrame, &slice, &remainder, CGRectGetHeight(hiddenRect), CGRectMaxYEdge);
    scrollView.frame = remainder;

    // Scroll the active text field into view.
    CGRect textFieldRect = [/* selected cell */ frame];
    [scrollView scrollRectToVisible:textFieldRect animated:YES];

    keyboardShown = YES;
}


// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
    // Reset the height of the scroll view to its original value
    UIScrollView *scrollView = (UIScrollView *) self.tableView;
    CGRect viewFrame = [scrollView frame];
    scrollView.frame = CGRectUnion(viewFrame, hiddenRect);

    keyboardShown = NO;
}
Respondida el 11/07/2009 a las 23:01
fuente por usuario

votos
4

Si usa una vista útil para colocar sus campos de texto ( de Jeff Lamarche ), puede desplazar la vista de tabla utilizando el método de delegado de esa manera.

(Nota: mis campos de texto se almacenan en una matriz con el mismo índice que there row en la vista de tabla)

- (void) textFieldDidBeginEditing:(UITextField *)textField
    {

        int index;
        for(UITextField *aField in textFields){

            if (textField == aField){
                index = [textFields indexOfObject:aField]-1;
            }
        }

         if(index >= 0) 
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

        [super textFieldDidBeginEditing:textField];
    }
Respondida el 01/05/2009 a las 07:09
fuente por usuario

votos
3

Una solución más fluida. Se desliza en los métodos de delegado UITextField, por lo que no es necesario desordenar las notificaciones w / UIKeyboard.

Notas de implementación:

kSettingsRowHeight: la altura de una UITableViewCell.

offsetTarget y offsetThreshold están deshabilitados de kSettingsRowHeight. Si usa una altura de fila diferente, establezca esos valores en la propiedad y del punto. [alt: calcula el desplazamiento de fila de una manera diferente.]

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
CGFloat offsetTarget    = 113.0f; // 3rd row
CGFloat offsetThreshold = 248.0f; // 6th row (i.e. 2nd-to-last row)

CGPoint point = [self.tableView convertPoint:CGPointZero fromView:textField];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

CGRect frame = self.tableView.frame;
if (point.y > offsetThreshold) {
    self.tableView.frame = CGRectMake(0.0f,
                      offsetTarget - point.y + kSettingsRowHeight,
                      frame.size.width,
                      frame.size.height);
} else if (point.y > offsetTarget) {
    self.tableView.frame = CGRectMake(0.0f,
                      offsetTarget - point.y,
                      frame.size.width,
                      frame.size.height);
} else {
    self.tableView.frame = CGRectMake(0.0f,
                      0.0f,
                      frame.size.width,
                      frame.size.height);
}

[UIView commitAnimations];

return YES;

}

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

[UIView beginAnimations:nil context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

CGRect frame = self.tableView.frame;
self.tableView.frame = CGRectMake(0.0f,
                  0.0f,
                  frame.size.width,
                  frame.size.height);

[UIView commitAnimations];

return YES;

}

Respondida el 04/08/2009 a las 08:18
fuente por usuario

votos
3

Me encontré con algo así como tu problema (quería una pantalla similar a la configuración de iPhone. Aplicación con un montón de celdas editables apiladas encima de otra) y descubrí que este enfoque funcionaba bien:

deslizando uitextfields alrededor para evitar

Respondida el 27/02/2009 a las 15:17
fuente por usuario

votos
2

Un ejemplo en Swift, utilizando el punto exacto del campo de texto de Get indexPath de UITextField en UITableViewCell con Swift :

func textFieldDidBeginEditing(textField: UITextField) {
    let pointInTable = textField.convertPoint(textField.bounds.origin, toView: self.accountsTableView)
    let textFieldIndexPath = self.accountsTableView.indexPathForRowAtPoint(pointInTable)
    accountsTableView.scrollToRowAtIndexPath(textFieldIndexPath!, atScrollPosition: .Top, animated: true)
}
Respondida el 21/05/2015 a las 06:34
fuente por usuario

votos
2

Muy interesante hilo de discusión, también se enfrentó al mismo problema puede ser peor porque

  1. Yo estaba usando una célula de medida y el campo de texto que estaba dentro.
  2. Tuve que usar UIViewController para satisfacer mis necesidades puede jugar por estar ventaja de UITableViewController.
  3. Tenía criterios de filtro / ordenar en mi celda de la tabla, es decir, las células ur sigue cambiando y hacer el seguimiento de la indexpath y todo no ayudarán.

Así que lea los hilos aquí y puesto en práctica mi versión, lo que me ayudó a empujar mis contenidos en el iPad en el paisaje de modo. Aquí está el código (esto no es a toda prueba y todo, pero lo arreglen mi problema) Primera u necesidad de tener un delegado en su clase de celda personalizado, que comienza en la edición, envía el campo de texto a ur viewcontroller y establecer el activefield = theTextField existe

// IMPLEMENTADO PARA MANIPULAR modo horizontal SOLAMENTE

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbValue = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect aRect = myTable.frame;

    CGSize kbSize = CGSizeMake(kbValue.height, kbValue.width);

    aRect.size.height -= kbSize.height+50;
// This will the exact rect in which your textfield is present
        CGRect rect =  [myTable convertRect:activeField.bounds fromView:activeField];
// Scroll up only if required
    if (!CGRectContainsPoint(aRect, rect.origin) ) {


            [myTable setContentOffset:CGPointMake(0.0, rect.origin.y) animated:YES];

    }


}

// Se llama cuando se envía el UIKeyboardWillHideNotification

- (void)keyboardWillHide:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    myTable.contentInset = contentInsets;
    myTable.scrollIndicatorInsets = contentInsets;
    NSDictionary* info = [aNotification userInfo];
    CGSize kbValue = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGSize kbSize = CGSizeMake(kbValue.height, kbValue.width);
    CGRect bkgndRect = activeField.superview.frame;
    bkgndRect.size.height += kbSize.height;
    [activeField.superview setFrame:bkgndRect];
    [myTable setContentOffset:CGPointMake(0.0, 10.0) animated:YES];
}

-anoop4real

Respondida el 17/07/2012 a las 18:11
fuente por usuario

votos
2

Este Soluton funciona para mí, tenga en cuenta la línea de

[tableView setContentOffset:CGPointMake(0.0, activeField.frame.origin.y-kbSize.height+160) animated:YES];

Puede cambiar el valor 160 para que coincida con que funcione con usted

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect bkgndRect = activeField.superview.frame;
                        bkgndRect.size.height += kbSize.height;
     [activeField.superview setFrame:bkgndRect];
     [tableView setContentOffset:CGPointMake(0.0, activeField.frame.origin.y-kbSize.height+160) animated:YES];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
   activeField = textField;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
 {
     activeField = nil;
 }
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    tableView.contentInset = contentInsets;
    tableView.scrollIndicatorInsets = contentInsets;
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect bkgndRect = activeField.superview.frame;
    //bkgndRect.size.height += kbSize.height;
    [activeField.superview setFrame:bkgndRect];
    [tableView setContentOffset:CGPointMake(0.0, activeField.frame.origin.y-kbSize.height) animated:YES];
}
Respondida el 02/12/2011 a las 19:28
fuente por usuario

votos
2

Dado que tiene campos de texto en una tabla, la mejor manera es cambiar el tamaño de la tabla, necesita establecer tableView.frame para que sea más pequeño en altura por el tamaño del teclado (creo que alrededor de 165 píxeles) y luego expandirlo nuevamente cuando el teclado se descarta

Opcionalmente, también puede deshabilitar la interacción del usuario para tableView en ese momento, si no desea que el usuario se desplace.

Respondida el 28/02/2009 a las 19:37
fuente por usuario

votos
1

Pequeña variación con Swift 4.2 ...

En mi UITableView tenía muchas secciones, pero tenía que evitar el efecto de cabecera flotante , así que utiliza un " dummyViewHeight enfoque" como se ve en otro lugar aquí en desbordamiento de pila ... Así que este es mi solución para este problema (también funciona para el teclado + sugerencias barra de herramientas +):

Declararemos como constante de la clase:

let dummyViewHeight: CGFloat = 40.0

Entonces

override func viewDidLoad() {
    super.viewDidLoad()
    //... some stuff here, not needed for this example

    // Create non floating header
    tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: dummyViewHeight))
    tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: 0, right: 0)

    addObservers()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    removeObservers()
}

Y aquí toda la magia ...

@objc func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        let keyboardHeight = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: dummyViewHeight))
        tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: keyboardHeight, right: 0)
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.25) {
        self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: self.dummyViewHeight))
        self.tableView.contentInset = UIEdgeInsets(top: -self.dummyViewHeight, left: 0, bottom: 0, right: 0)
    }
}
Respondida el 08/10/2018 a las 10:45
fuente por usuario

votos
1

en viewDidLoad

-(void)viewdidload{

[super viewdidload];

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

    -(void)keyboardWillChange:(NSNotification*)sender{

        NSLog(@"keyboardwillchange sender %@",sender);

float margin=0  // set your own topmargin


        CGFloat originY = [[sender.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;


        if (originY >= self.view.frame.size.height){

            NSLog(@"keyboardclose");



            [tb_ setFrame:CGRectMake(0, margin, self.view.frame.size.width, self.view.frame.size.height-margin)];

        }else{

            NSLog(@"keyobard on");

            float adjustedHeight = self.view.frame.size.height - margin - (self.view.frame.size.height-originY);

            [tb_ setFrame:CGRectMake(0, margin, self.view.frame.size.width, adjustedHeight)];
        }







    }
Respondida el 12/02/2016 a las 06:14
fuente por usuario

votos
1

Estoy usando éstos y funcionan como un encanto:

BSKeyboardControls - BSKeyboardControls github

TPKeyboardAvoiding - TPKeyboardAvoiding github

Respondida el 13/02/2014 a las 09:30
fuente por usuario

votos
1

Yo uso esta frecuencia en mis proyectos. Esta solución funciona con scrollviews, tableviews o collectionviews y es fácil de configurar. También se engancha automáticamente botones arriba “Siguiente” en el teclado para cambiar a través de los campos de texto.

Compruébelo aquí

Respondida el 12/02/2014 a las 21:27
fuente por usuario

votos
1

Voy a tirar mi solución (O QuickDialog de que es) en el sombrero. Básicamente esperar para animar al desplazamiento. Sería bueno para conseguir la animación JIT teclado en lugar del número mágico.

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.emailTextField) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 50 * USEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        });
    }
}
Respondida el 28/01/2014 a las 19:05
fuente por usuario

votos
1

solución fácil y rápida.

Yo sólo tiene que desplazarse a la celda de la derecha cada vez que ocurre el desplazamiento

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView 

Suponiendo que sé mesa ahora está en este modo "_keepMyCellOnTop" y que sé celda seleccionada "_selectedCellIndex" o desplazarse a la celda seleccionada

- (void)scrollViewDidScroll:(UIScrollView *)scrollView 
{

    if (_keepMyCellOnTop)
    {
        [self.tableView scrollToRowAtIndexPath:_selectedCellIndex atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

Esto evitará el desplazamiento.

Al colocar el código en -(void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView el resultado es de desplazamiento hacia arriba y hacia abajo

Respondida el 31/12/2013 a las 13:37
fuente por usuario

votos
1

acabo de resolver este problema por mí mismo después de que me he referido una masa de soluciones encontradas a través de Google y de desbordamiento de pila.

En primer lugar, por favor, comprueba que has establecido un IBOutlet de su UIScrollView, entonces eche un vistazo de cerca a Manzana Doc: Gestión del teclado . Por último, si usted puede desplazarse por el fondo, pero el teclado todavía cubre el campos de texto, por favor, eche un vistazo a esta pieza de código:

// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;

if (aRect.size.height < activeField.frame.origin.y+activeField.frame.size.height) {

    CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y+activeField.frame.size.height-aRect.size.height);

    [scrollView setContentOffset:scrollPoint animated:YES];

La diferencia principal entre esta pieza y la mentira de Apple en el caso de condiciones. Creo que el cálculo de la distancia de desplazamiento de la manzana y la condición de que el campo de texto cubierto por teclado no son exactos, así que hice mi modificación que el anterior.

Déjame saber si funciona

Respondida el 18/08/2012 a las 11:10
fuente por usuario

votos
1

Aquí es cómo hice este trabajo, que es una mezcla de Sam Ho y respuestas de Marcel W, y algunos de mis propias correcciones de errores realizados en mi código de mierda. Yo estaba usando un UITableViewController. Ahora, la tabla cambia de tamaño correctamente cuando se muestra el teclado.

1) En viewDidLoadañadí:

self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

2) Me había olvidado de llamar a los superequivalentes en viewWillAppeary awakeFromNib. Añadí éstos de nuevo.

Respondida el 26/07/2012 a las 18:18
fuente por usuario

votos
1

Si su UITableView es administrado por una subclase de UITableViewController y no UITableView, y el delegado campo de texto es el UITableViewController, debe gestionar todos los desplazan automáticamente - todos estos otros comentarios son muy difíciles de implementar en la práctica.

Para un buen ejemplo ver el proyecto de código de ejemplo de manzana: TaggedLocations.

Se puede ver que se desplaza de forma automática, pero no parece haber ningún código que hace esto. Este proyecto también tiene celdas de la vista encargo de la tabla, por lo que si usted construye su aplicación con él como guía, se debe obtener el resultado deseado.

Respondida el 05/03/2012 a las 07:09
fuente por usuario

votos
1

Otro método sencillo (sólo funciona con una sección)

//cellForRowAtIndexPath
UItextField *tf;
[cell addSubview:tf];
tf.tag = indexPath.row;
tf.delegate = self;

//textFieldDidBeginEditing:(UITextField *)text
[[self.tableView scrollToRowsAtIndexPath:[NSIndexPath indexPathForRow:text.tag in section:SECTIONINTEGER] animated:YES];
Respondida el 23/11/2011 a las 17:25
fuente por usuario

votos
1

Así que después de horas de trabajo agotador tratar de utilizar estas soluciones actuales (y no completamente) que finalmente me dieron las cosas funcionan bien, y los actualiza para utilizar los nuevos bloques de animación. Mi respuesta se basa totalmente en la respuesta de Ortwin anterior .

Así, por la razón que sea el código anterior fue simplemente no funciona para mí. Mi configuración parecía bastante similar a otros, pero tal vez porque yo estaba en un iPad o 4.3 ... ni idea. Se estaba haciendo un poco de matemática loco y disparar mi tableview fuera de la pantalla.

Ver resultado final de mi solución: http://screencast.com/t/hjBCuRrPC (Por favor, ignore la foto :-P).

Así que fui a la esencia de lo que estaba haciendo Ortwin, pero ha cambiado la forma en que estaba haciendo un poco de matemática de sumar la origin.y y size.height de mi vista de tabla con la altura del teclado. Cuando le resto de la altura de la ventana de ese resultado, me dice lo mucho que he intersección pasando. Si su mayor que 0 (también conocido como existe un cierto solapamiento) llevo a cabo la animación de la altura del marco.

Además hubo algunos problemas de actualización que fueron resueltos por 1) esperando para desplazarse a la celda hasta que se hizo la animación y 2) usando la opción UIViewAnimationOptionBeginFromCurrentState al ocultar el teclado.

Un par de cosas a tener en cuenta.

  • _topmostRowBeforeKeyboardWasShown y _originalFrame son variables de instancia declarados en el encabezamiento.
  • self.guestEntryTableView es mi tableView (estoy en un archivo externo)
  • IASKCGRectSwap es el método de Ortwin para voltear las coordenadas de un marco
  • Sólo actualizar la altura de la tableView si al menos 50px de que va a estar mostrando
  • Ya que no estoy en un UIViewController no tengo self.view, por lo que sólo devolver el tableView a su marco original

Una vez más, no habría conseguido cerca de esta respuesta si Ortwin no proporcionó el quid de la cuestión. Aquí está el código:

- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    self.activeTextField = textField;

    if ([self.guestEntryTableView indexPathsForVisibleRows].count) {
        _topmostRowBeforeKeyboardWasShown = (NSIndexPath*)[[self.guestEntryTableView indexPathsForVisibleRows] objectAtIndex:0];
    } else {
        // this should never happen
        _topmostRowBeforeKeyboardWasShown = [NSIndexPath indexPathForRow:0 inSection:0];
        [textField resignFirstResponder];
    }
}

- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    self.activeTextField = nil;
}

- (void)keyboardWillShow:(NSNotification*)notification {
    NSDictionary* userInfo = [notification userInfo];

    NSValue* keyboardFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    // Reduce the tableView height by the part of the keyboard that actually covers the tableView
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect windowRect = [[UIApplication sharedApplication] keyWindow].bounds;
    CGRect viewRectAbsolute = [self.guestEntryTableView convertRect:self.guestEntryTableView.bounds toView:[[UIApplication sharedApplication] keyWindow]];
    CGRect keyboardFrame = [keyboardFrameValue CGRectValue];
    if (UIInterfaceOrientationLandscapeLeft == orientation ||UIInterfaceOrientationLandscapeRight == orientation ) {
        windowRect = IASKCGRectSwap(windowRect);
        viewRectAbsolute = IASKCGRectSwap(viewRectAbsolute);
        keyboardFrame = IASKCGRectSwap(keyboardFrame);
    }

    // fix the coordinates of our rect to have a top left origin 0,0
    viewRectAbsolute = FixOriginRotation(viewRectAbsolute, orientation, windowRect.size.width, windowRect.size.height);

    CGRect frame = self.guestEntryTableView.frame;
    _originalFrame = self.guestEntryTableView.frame;

    int remainder = (viewRectAbsolute.origin.y + viewRectAbsolute.size.height + keyboardFrame.size.height) - windowRect.size.height;

    if (remainder > 0 && !(remainder > frame.size.height + 50)) {
        frame.size.height = frame.size.height - remainder;
        float duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        [UIView animateWithDuration: duration
                        animations:^{
                            self.guestEntryTableView.frame = frame;
                        }
                        completion:^(BOOL finished){
                            UITableViewCell *textFieldCell = (UITableViewCell*) [[self.activeTextField superview] superview];
                            NSIndexPath *textFieldIndexPath = [self.guestEntryTableView indexPathForCell:textFieldCell];
                            [self.guestEntryTableView scrollToRowAtIndexPath:textFieldIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
                        }];
    }

}

- (void)keyboardWillHide:(NSNotification*)notification {
    NSDictionary* userInfo = [notification userInfo];
    float duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration: duration
                          delay: 0.0
                        options: (UIViewAnimationOptionBeginFromCurrentState)
                     animations:^{
                         self.guestEntryTableView.frame = _originalFrame;
                     }
                     completion:^(BOOL finished){
                         [self.guestEntryTableView scrollToRowAtIndexPath:_topmostRowBeforeKeyboardWasShown atScrollPosition:UITableViewScrollPositionTop animated:YES];
                     }];

}   

#pragma mark CGRect Utility function
CGRect IASKCGRectSwap(CGRect rect) {
    CGRect newRect;
    newRect.origin.x = rect.origin.y;
    newRect.origin.y = rect.origin.x;
    newRect.size.width = rect.size.height;
    newRect.size.height = rect.size.width;
    return newRect;
}

CGRect FixOriginRotation(CGRect rect, UIInterfaceOrientation orientation, int parentWidth, int parentHeight) {
    CGRect newRect;
    switch(orientation)
    {
        case UIInterfaceOrientationLandscapeLeft:
            newRect = CGRectMake(parentWidth - (rect.size.width + rect.origin.x), rect.origin.y, rect.size.width, rect.size.height);
            break;
        case UIInterfaceOrientationLandscapeRight:
            newRect = CGRectMake(rect.origin.x, parentHeight - (rect.size.height + rect.origin.y), rect.size.width, rect.size.height);
            break;
        case UIInterfaceOrientationPortrait:
            newRect = rect;
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
            newRect = CGRectMake(parentWidth - (rect.size.width + rect.origin.x), parentHeight - (rect.size.height + rect.origin.y), rect.size.width, rect.size.height);
            break;
    }
    return newRect;
}
Respondida el 18/07/2011 a las 09:45
fuente por usuario

votos
1

He intentado casi el mismo enfoque y se acercó con un código más simple y más pequeño para el mismo. He creado un IBOutlet iTextView y se asocia con la UITextView en el IB.

 -(void)keyboardWillShow:(NSNotification *)notification
    {
        NSLog(@"Keyboard");
        CGRect keyFrame = [[[notification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

        [UIView beginAnimations:@"resize view" context:nil];
        [UIView setAnimationCurve:1];
        [UIView setAnimationDuration:1.0];
        CGRect frame = iTableView.frame;
        frame.size.height = frame.size.height -  keyFrame.size.height;
        iTableView.frame = frame;
        [iTableView scrollRectToVisible:frame animated:YES];
        [UIView commitAnimations];

    }
Respondida el 13/05/2011 a las 06:00
fuente por usuario

votos
1

Esto funciona perfectamente, y en el iPad también.

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

    if(textField == textfield1){
            [accountName1TextField becomeFirstResponder];
        }else if(textField == textfield2){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield3 becomeFirstResponder];

        }else if(textField == textfield3){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield4 becomeFirstResponder];

        }else if(textField == textfield4){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield5 becomeFirstResponder];

        }else if(textField == textfield5){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield6 becomeFirstResponder];

        }else if(textField == textfield6){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield7 becomeFirstResponder];

        }else if(textField == textfield7){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield8 becomeFirstResponder];

        }else if(textField == textfield8){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:6 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield9 becomeFirstResponder];

        }else if(textField == textfield9){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:7 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textField resignFirstResponder];
        }
Respondida el 23/10/2010 a las 08:11
fuente por usuario

votos
0

Acabo de descubrir otro error al utilizar UITableViewController. No se desplazan automáticamente cuando el teclado se presentó. Me di cuenta de que era debido a contentInsetAdjustmentBehavior = .Nunca en UITableView.

Respondida el 03/07/2019 a las 21:30
fuente por usuario

votos
0

Solución para Swift 3-4 con animaciones y cambiante marco del teclado:

En primer lugar, crear un Bool:

// MARK: - Private Properties
private var isKeyboardShowing = false

En segundo lugar, añadir observadores a las notificaciones teclado del sistema:

// MARK: - Overriding ViewController Life Cycle Methods
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: .UIKeyboardWillChangeFrame, object: nil)
}

En tercer lugar, preparar la función de animación:

func adjustTableViewInsets(keyboardHeight: CGFloat, duration: NSNumber, curve: NSNumber){
    var extraHeight: CGFloat = 0
    if keyboardHeight > 0 {
        extraHeight = 20
        isKeyboardShowing = true
    } else {
        isKeyboardShowing = false
    }

    let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight + extraHeight, right: 0)
    func animateFunc() {
        //refresh constraints
        //self.view.layoutSubviews()
        tableView.contentInset = contentInset
    }

    UIView.animate(withDuration: TimeInterval(duration), delay: 0, options: [UIViewAnimationOptions(rawValue: UInt(curve))], animations: animateFunc, completion: nil)
}

A continuación, añadir los métodos objetivo / acción (llamada por los observadores):

// MARK: - Target/Selector Actions
func keyboardWillShow(notification: NSNotification) {
    if !isKeyboardShowing {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height

            let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
            let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber

            adjustTableViewInsets(keyboardHeight: keyboardHeight, duration: duration, curve: curve)
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
    let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
    adjustTableViewInsets(keyboardHeight: 0, duration: duration, curve: curve)
}

func keyboardWillChangeFrame(notification: NSNotification) {
    if isKeyboardShowing {
        let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber

        if let newKeyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = newKeyboardSize.height
            adjustTableViewInsets(keyboardHeight: keyboardHeight, duration: duration, curve: curve)
        }
    }
}

Por último, no se olvide de quitar los observadores en deinit o en viewWillDisappear:

deinit {
    NotificationCenter.default.removeObserver(self)
}
Respondida el 10/06/2018 a las 15:48
fuente por usuario

votos
0

No hay necesidad de ningún cálculo, utilice el código de abajo va a trabajar: Este código que utilicé en mi personalizada UITableViewCell, está funcionando:

override func viewDidLoad() {
super.viewDidLoad()

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)}


func keyboardWillShow(_ notification:Notification) {

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
    tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
}}


func keyboardWillHide(_ notification:Notification) {

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
    tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
}}
Respondida el 22/02/2018 a las 04:47
fuente por usuario

votos
0

Swift 4 solución completa:

  • Correctamente trabaja con cambios marco del teclado (por ejemplo, altura del teclado cambia como emojii → teclado normal).
  • TabBar apoyo y barra de herramientas, por ejemplo UITableView (en otros ejemplos que recibe inserciones incorrectas).
  • duración de la animación dinámica (no modificable).
  • Protocolo orientado, por lo que puede utilizar fácilmente en cualquier situación.
  • inserciones de desplazamiento también funciona.

Escribí protocolo helper (puedes descargarlo como lo esencial , porque es demasiado grande como para publicar en StackOverflow), por lo que su vista sólo tiene que:

  1. Adoptar KeyboardChangeFrameObserverprotocolo:

    func willChangeKeyboardFrame(height: CGFloat, animationDuration: TimeInterval, animationOptions: UIViewAnimationOptions)
    
  2. Llamar observeKeyboardFrameChanges()en aparecer.

ejemplo de implementación de protocolo para que tableView:

class TestViewController: UITableViewController, KeyboardChangeFrameObserver {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        observeKeyboardFrameChanges()
    }

    func willChangeKeyboardFrame(height: CGFloat, animationDuration: TimeInterval, animationOptions: UIViewAnimationOptions) {
        var adjustedHeight = height

        if let tabBarHeight = self.tabBarController?.tabBar.frame.height {
            adjustedHeight -= tabBarHeight
        } else if let toolbarHeight = navigationController?.toolbar.frame.height, navigationController?.isToolbarHidden == false {
            adjustedHeight -= toolbarHeight
        }

        if adjustedHeight < 0 { adjustedHeight = 0 }

        UIView.animate(withDuration: animationDuration, animations: {
            let newInsets = UIEdgeInsets(top: 0, left: 0, bottom: adjustedHeight, right: 0)
            self.tableView.contentInset = newInsets
            self.tableView.scrollIndicatorInsets = newInsets
        })
    }

}
Respondida el 11/01/2018 a las 21:10
fuente por usuario

votos
0
// scroll tableview so content ends at the middle of the tableview (out of the way of the keyboard)
CGPoint newContentOffset = CGPointMake(0, [self.tableView contentSize].height - (self.tableView.bounds.size.height / 2));
[self.tableView setContentOffset:newContentOffset animated:YES];
Respondida el 27/06/2017 a las 18:12
fuente por usuario

votos
0

Mira mi versión :)

    - (void)keyboardWasShown:(NSNotification *)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect bkgndRect = cellSelected.superview.frame;
    bkgndRect.size.height += kbSize.height;
    [cellSelected.superview setFrame:bkgndRect];
    [tableView setContentOffset:CGPointMake(0.0, cellSelected.frame.origin.y-kbSize.height) animated:YES];
}


- (void)keyboardWasHidden:(NSNotification *)aNotification
{
    [tableView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
}
Respondida el 02/07/2016 a las 17:32
fuente por usuario

votos
0

Aquí está mi solución inspirada en la pantalla "Editar evento" de iOS7 aplicación Calendario.

Uno de los puntos clave de esta solución es que el teclado es despedido cuando la tabla usuario se desplaza.

Implementación:

1) Añadir propiedad que almacenará campo de texto seleccionado:

@property (strong) UITextField *currentTextField;

y variables BOOL que vamos a utilizar para comprobar si necesitamos para ocultar el teclado cuando la tabla usuario se desplaza.

BOOL hideKeyboardOnScroll;

2) Manejar las devoluciones de llamada de delegado UITextField:

#pragma mark - UITextFieldDelegate

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

- (void) textFieldDidEndEditing: (UITextField *) textField {
    self.currentTextField = nil;
}

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

    CGPoint newContentOffset = CGPointZero;
    if (tableView.contentSize.height > tableView.frame.size.height) {
        newContentOffset.y = MIN(tableView.contentOffset.y, tableView.contentSize.height - tableView.frame.size.height);
    }
    [tableView setContentOffset: newContentOffset animated: YES];

    return YES;
}

3) de la manija método UIScrollViewDelegate para comprobar que vista de desplazamiento del usuario.

#pragma mark - UIScrollViewDelegate

- (void) scrollViewDidScroll: (UIScrollView *) scrollView {
    if (hideKeyboardOnScroll == YES) {
        [self.currentTextField resignFirstResponder];
    }
}

4) Suscribirse a las notificaciones de teclado en el método de viewcontroller [viewWillAppear] y darse de baja en el método [viewWillDisappear].

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

    [ [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];

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

5) Manejar las notificaciones de teclado:

- (void) keyboardWillShow: (NSNotification *) notification {
    CGRect keyboardFrame = [ [ [notification userInfo] objectForKey: UIKeyboardFrameBeginUserInfoKey] CGRectValue];

    // Find cell with textfield.
    CGRect textFieldFrame = [tableView convertRect: self.currentTextField.frame fromView: self.currentTextField];
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint: textFieldFrame.origin];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath: indexPath];
    //

    // Shrink tableView size.
    CGRect tableViewFrame = tableView.frame;
    tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width,
                             self.view.frame.size.height - tableView.frame.origin.y - keyboardFrame.size.height);
    //

    // Check if cell is visible in shrinked table size.
    BOOL cellIsFullyVisible = YES;
    if ( cell.frame.origin.y < tableView.contentOffset.y ||
        (cell.frame.origin.y + cell.frame.size.height) > (tableView.contentOffset.y + tableView.frame.size.height) ) {
        cellIsFullyVisible = NO;
    }
    //

    // If cell is not fully visible when scroll table to show cell;
    if (cellIsFullyVisible == NO) {
        CGPoint contentOffset = CGPointMake(tableView.contentOffset.x, CGRectGetMaxY(cell.frame) - tableView.frame.size.height);
        if (cell.frame.origin.y < tableView.contentOffset.y) {
            contentOffset.y = cell.frame.origin.y;
        }
        contentOffset.y = MAX(0, contentOffset.y);

        // For some reason [setContentOffset] is called without delay then
        // this code may not work for some cells. That why we call it with brief delay.
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [UIView animateWithDuration: 0.5 animations:^{
                [tableView setContentOffset: contentOffset animated: NO];
            } completion: ^(BOOL finished) {
                hideKeyboardOnScroll = YES;
            }];
        });
    } else {
        hideKeyboardOnScroll = YES;
    }
    //

    // Finally restore original table frame.
    tableView.frame = tableViewFrame;
    //
}

- (void) keyboardWillHide: (NSNotification *) notification {
    [super keyboardWillHide: notification];

    hideKeyboardOnScroll = NO;
}
Respondida el 21/08/2014 a las 15:43
fuente por usuario

votos
0

Creo que la mejor manera es a través UITableViewController.

Si quieres un UITableView en una UIViewController , simplemente hacer una ContentView con un UITableViewController incrustado y poner las siguientes líneas en el viedDidLoad del UIViewController:

self.tableView = ((UITableViewController*)self.childViewControllers[0]).tableView;
self.tableView.delegate = self;
self.tableView.dataSource = self;

Fácil;)

Respondida el 06/06/2014 a las 16:29
fuente por usuario

votos
0

Creo que no hay una manera "correcta" de hacerlo. Tienes que elegir la mejor solución de ajuste para su caso de uso. En mi iPad App tengo una UIViewControllerque se presenta como modal UIModalPresentationFormSheety consiste en una UITableView. Esta tabla contiene dos UITextFieldspor célula. Sólo llamaba scrollToRowAtIndexPath:atScrollPosition:animated:en el textFieldDidBeginEditing:método no funciona para mí. Por tanto, he creado una tableFooterView:

- (void)viewDidLoad
{
    [super viewDidLoad];

    m_footerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, m_tableView.frame.size.width, 300.0f)];
    [m_footerView setBackgroundColor:[UIColor clearColor]];
    [m_tableView setTableFooterView:m_footerView];
    [m_footerView release];
}

La idea es que el teclado se esconde el tableFooterViewy no el UITextFields. Por lo que el tableFooterViewdebe ser lo suficientemente alta. Después de que se puede utilizar scrollToRowAtIndexPath:atScrollPosition:animated:en el textFieldDidBeginEditing:método.

Creo que también es posible mostrar y ocultar la tableFooterViewdinámica mediante la adición de los observadores de las notificaciones de teclado, pero no he probado todavía:

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

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

- (void)keyboardWillShow:(NSNotification *)notification 
{
     [m_tableView setTableFooterView:m_footerView];
}

- (void)keyboardWillHide:(NSNotification *)notification 
{
     [m_tableView setTableFooterView:nil];
}

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

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
Respondida el 15/09/2012 a las 08:51
fuente por usuario

votos
0

i hizo crear un pequeño proyecto que resuelve este problema con el teclado, en mi caso yo sólo necesito hacer la vista de tabla subir cuando el teclado se muestra.

¡Espero que esto ayude!

http://git.io/BrH9eQ

Respondida el 19/11/2011 a las 21:21
fuente por usuario

votos
0

Acabo de mirar de nuevo en el iOS 5.0 referencia lib y encontré esta sección titulada "El contenido que se encuentra debajo del teclado en movimiento": TextAndWebiPhoneOS KeyboardManagement

Es este nuevo desde iOS 5, tal vez? No he leído en ella sin embargo, como estoy en el medio de algo más, pero quizás otros saber más y para mí y otros pueden iluminar aquí.

¿El documento de Apple reemplaza lo que se ha discutido aquí o es la información que aquí sigue siendo útil para los usuarios de iOS 5 SDK?

Respondida el 26/10/2011 a las 12:07
fuente por usuario

votos
0

UITableViewControllerhace el desplazamiento de forma automática, por cierto. La diferencia en comparación con el uso de un UIViewControllerdecir, que usted tiene que crear navbar-Buttonitems programación utilizando el NavigationController, cuando se utiliza una TableViewController.

Respondida el 20/03/2011 a las 20:59
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more