Faire un rouleau UITableView lorsque le champ de texte est sélectionné

voix
228

Je donne et poser la question après beaucoup d'essais et d'erreurs,. Je l'ai vu beaucoup de personnes ayant des problèmes similaires, mais ne peuvent pas obtenir toutes les réponses à travailler à droite.

J'ai un UITableViewqui est composé de cellules personnalisées. Les cellules sont faites de 5 champs de texte à côté de l'autre (comme une sorte de grille).

Lorsque je tente de faire défiler et modifier les cellules au fond de la UITableView, je ne parviens pas à obtenir mes cellules correctement positionnées au- dessus du clavier.

J'ai vu beaucoup de réponses parler de l'évolution des tailles de vue, etc ... mais aucun d'entre eux a travaillé bien jusqu'à présent.

Quelqu'un pourrait clarifier la « bonne » façon de le faire avec un exemple de code concret?

Créé 27/02/2009 à 11:05
source utilisateur
Dans d'autres langues...                            


48 réponses

voix
110

Si vous utilisez UITableViewController au lieu de UIViewController, il le fera automatiquement si.

Créé 21/09/2010 à 04:42
source utilisateur

voix
89

La fonction qui fait le défilement pourrait être beaucoup plus 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];
}

C'est tout. Aucun calcul du tout.

Créé 15/04/2009 à 13:21
source utilisateur

voix
65

Je fais quelque chose de très similaire, il est générique, pas besoin de calculer quelque chose de spécifique pour votre code. Il suffit de consulter les remarques sur le code:

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 1.2+ Version:

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()
        }
    }
}
Créé 13/04/2010 à 15:46
source utilisateur

voix
41

J'ai eu le même problème, mais remarqué qu'il apparaît dans une seule vue. Alors j'ai commencé à chercher les différences entre les contrôleurs.

J'ai découvert que le comportement de défilement est dans - (void)viewWillAppear:(BOOL)animatedde l'instance super.

Assurez-vous donc de mettre en œuvre comme ceci:

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

Et il n'a pas d' importance si vous utilisez UIViewControllerou UITableViewController; vérifié en mettant un UITableViewen tant que sous - vue self.view UIViewController. Ce fut le même comportement. La vue ne permet pas de faire défiler si l'appel [super viewWillAppear:animated];était absent.

Créé 29/05/2011 à 01:42
source utilisateur

voix
37

i peut-être manqué, comme je ne l'ai pas lu ici tout le poste, mais ce que je suis venu avec semble trompeusement simple. Je ne l'ai pas mis ce dans le tordeur, tester dans toutes les situations, mais il semble que cela devrait fonctionner très bien.

il suffit de régler la contentInset du tableview par la hauteur du clavier, puis faites défiler la cellule vers le bas:

- (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];
}

et bien sûr

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

est-ce aussi simple? suis-je manque quelque chose? jusqu'à présent, il travaille pour moi bien, mais comme je l'ai dit, je n'ai pas le mettre dans le tordeur ...

Créé 18/08/2012 à 01:12
source utilisateur

voix
35

La solution la plus simple pour Swift 3 , basée sur la solution 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)
    })
}
Créé 08/12/2016 à 13:26
source utilisateur

voix
34

Si vous pouvez utiliser UITableViewController, vous obtenez la fonctionnalité gratuitement. Parfois, cependant, ce n'est pas une option, en particulier si vous avez besoin de plusieurs points de vue non seulement le UITableView.

Certaines des solutions présentées ici ne fonctionnent pas sur iOS ≥4, certains ne fonctionnent pas sur iPad ou en mode paysage, certains ne fonctionnent pas pour les claviers Bluetooth (où nous ne voulons pas de défilement), d' autres pas travail lors de la commutation entre plusieurs champs de texte. Donc , si vous choisissez une solution, assurez - vous de tester ces cas. Ceci est la solution que nous utilisons utilisé dans 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];
    }
}   

Voici le code complet de la classe en InAppSettingsKit. Pour le tester, utilisez le volet enfant « Liste complète » où vous pouvez tester les scénarios mentionnés ci - dessus.

Créé 13/12/2010 à 17:01
source utilisateur

voix
34

Je pense que je suis venu avec la solution pour correspondre au comportement des applications d'Apple.

Tout d'abord, dans votre viewWillAppear: abonnez-vous aux notifications de clavier, de sorte que vous savez quand le clavier affichera et se cacher, et le système vous indiquera la taille du clavier, mais ne » oubliez pas de désenregistrer dans votre viewWillDisappear :.

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

Mettre en œuvre les méthodes similaires au-dessous afin que vous ajuster la taille de votre tableView pour correspondre à la zone visible une fois les spectacles du clavier. Ici, je suis suivi de l'état du clavier séparément afin que je puisse choisir quand régler le tableView revenir à hauteur moi-même, puisque vous obtenez ces notifications sur tous les changements sur le terrain. Ne pas oublier de mettre en œuvre keyboardWillHide: et choisir un endroit approprié pour fixer votre taille 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];
    }
}

Maintenant, voici le bit de défilement, nous travaillons sur quelques tailles d'abord, nous voyons où nous sommes dans la zone visible et définissez les rect que nous voulons défiler jusqu'à être soit la demi-vue au-dessus ou en dessous du milieu du champ de texte basé l'endroit où il est dans la vue. Dans ce cas, nous avons un tableau de UITextFields et un ENUM qui garde la trace d'eux, donc multiplier le rowHeight par le numéro de ligne nous donne le décalage réel du cadre dans ce point de vue extérieur.

- (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];
}

Cela semble fonctionner assez bien.

Créé 23/03/2009 à 02:49
source utilisateur

voix
22

La solution la plus simple pour 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
    }
Créé 25/08/2015 à 06:42
source utilisateur

voix
6

J'espère que vous avez déjà une lecture solution tous ceux. Mais j'ai trouvé ma solution comme suit. J'attends que vous avez déjà une cellule avec UITextField. Donc , sur la préparation juste garder l'index de ligne dans l'étiquette du champ de texte.

cell.textField.tag = IndexPath.row;

Créer une activeTextField, instance de UITextFieldavec une portée mondiale comme ci - dessous:

@interface EditViewController (){

    UITextField *activeTextField;

}

Donc, maintenant que vous venez de copier coller mon code à la fin. Et ne pas oublier d'ajouterUITextFieldDelegate

#pragma mark - TextField Delegation

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

    activeTextField = textField;

    return YES;
}

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

    activeTextField = nil;

}

clavier registres 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];



}

Poignées clavier Notifications:

Appelé lorsque l' UIKeyboardDidShowNotificationenvoi.

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

}

Appelée lorsque le UIKeyboardWillHideNotificationest envoyé

- (void)keyboardWillBeHidden:(NSNotification*)aNotification

{

    UIEdgeInsets contentInsets = UIEdgeInsetsZero;

    [self.tableView setContentInset:contentInsets];

    [self.tableView setScrollIndicatorInsets:contentInsets];

}

Maintenant , une chose est à gauche, Appelez la registerForKeyboardNotificationsméthode pour la ViewDidLoadméthode comme suit:

- (void)viewDidLoad {

    [super viewDidLoad];

    // Registering keyboard notification

    [self registerForKeyboardNotifications];

    // Your codes here...

}

Vous avez terminé, espérons que votre textFieldsvolonté ne plus caché par le clavier.

Créé 03/01/2015 à 21:36
source utilisateur

voix
6

La combinaison et remplir les blancs de plusieurs réponses (en particulier Ortwin Gentz, l'utilisateur 98013) et un autre poste, cela fonctionnera de la boîte pour SDK 4.3 sur un iPad en mode portrait ou paysage:

@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
Créé 03/08/2011 à 03:35
source utilisateur

voix
5

Mon approche:

Je suis sous-classe UITextField et ajouter une propriété indexPath. Dans la CellFor ... i Méthode propriété main sur la indexPath.

Puis ajouter le code suivant:

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);}];

au textFieldShould / WillBegin ... etc.

Lorsque le clavier vous devez inverser disparaît avec:

[UIView animateWithDuration:0.3 animations:^(void){self.tableView.contentOffset = CGPointMake(0, 0);}];
Créé 29/09/2012 à 13:03
source utilisateur

voix
4

Utiliser la UITextField's delegateméthode:

Rapide

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
}

Objectif c

- (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;
}
Créé 20/03/2015 à 07:00
source utilisateur

voix
4

La bonne réponse est la réponse de Sam Ho:

« Si vous utilisez UITableViewController au lieu de UIViewController, il le fera automatiquement si. ».

Assurez-vous de connecter votre UITableView à la propriété TableView du UITableViewController (donc par exemple ne pas ajouter comme une sous-vue de la propriété Vue de la UITableViewController).

Assurez-vous également de définir la propriété AutoresizingMask de votre UITableView à FlexibleHeight

Créé 09/12/2010 à 11:28
source utilisateur

voix
4

Si vous utilisez Three20, puis utilisez la autoresizesForKeyboardpropriété. Il suffit de définir dans le votre contrôleur de vue -initWithNibName:bundlede la méthode

self.autoresizesForKeyboard = YES

Cela prend en charge:

  1. À l'écoute des notifications de clavier et d'ajuster le cadre de la vue de la table
  2. Faire défiler au premier répondeur

Fait et fait.

Créé 21/09/2010 à 14:19
source utilisateur

voix
4

notifications de clavier fonctionnent, mais le code exemple d'Apple pour qui suppose que la vue de défilement est la vue racine de la fenêtre. Ceci est généralement pas le cas. Vous devez compenser les barres d'onglets, etc., pour obtenir le bon décalage.

Il est plus facile qu'il n'y paraît. Voici le code que j'utilise dans un UITableViewController. Il a deux variables d'instance, hiddenRect et 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;
}
Créé 11/07/2009 à 23:01
source utilisateur

voix
4

Si vous utilisez un uitableview pour placer vos textfields ( de Jeff Lamarche ), vous pouvez simplement faire défiler la tableview selon la méthode du délégué comme si.

(Remarque: mes champs de texte sont stockés dans un tableau avec le même indice que là ligne dans la tableview)

- (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];
    }
Créé 01/05/2009 à 07:09
source utilisateur

voix
3

Une solution plus rationalisée. Il se glisse dans les méthodes de délégué UITextField, il ne nécessite pas déconner w / notifications UIKeyboard.

Notes de mise en œuvre:

kSettingsRowHeight - la hauteur d'un UITableViewCell.

offsetTarget et offsetThreshold sont baed hors de kSettingsRowHeight. Si vous utilisez une hauteur de ligne différente, définissez ces valeurs à la propriété du point d'y. [Alt: Calcul de la ligne de décalage d'une manière différente.]

- (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;

}

Créé 04/08/2009 à 08:18
source utilisateur

voix
3

Je suis tombé sur quelque chose comme votre problème (je voulais un écran similaire à settings.app de l'iPhone avec un tas de cellules modifiables empilés sur le dessus d'une autre) et a constaté que cette approche a bien fonctionné:

UITextFields coulissant autour d'éviter

Créé 27/02/2009 à 15:17
source utilisateur

voix
2

Un exemple à Swift, en utilisant le point exact du champ de texte de Get indexPath de UITextField à UITableViewCell avec 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)
}
Créé 21/05/2015 à 06:34
source utilisateur

voix
2

fil de discussion très intéressante, j'ai aussi fait face au même problème peut être pire parce que

  1. J'utilisais une cellule personnalisée et le TextField trouvait à l'intérieur.
  2. Je devais utiliser UIViewController pour répondre à mes besoins donc je ne peux tirer parti de UITableViewController.
  3. J'ai eu critères filtre / trier dans ma cellule de table, les cellules ie ur continue à changer et de garder une trace de l'indexPath et tout ne va pas aider.

Alors , lisez les fils ici et mis en œuvre ma version, ce qui m'a aidé à pousser mes contenus dans l' iPad en paysage en mode. Voici le code (ce qui est fou pas une preuve et tout, mais il a fixé mon problème) Tout d' abord u besoin d'avoir un délégué dans votre classe de cellule personnalisée, qui sur l' édition commence, envoie le champ de texte à ur viewcontroller et régler la ActiveField = theTextField il

// MANIPULER PAYSAGE MIS EN ŒUVRE MODE SEULEMENT

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

    }


}

// Appelée lorsque le UIKeyboardWillHideNotification est envoyé

- (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

Créé 17/07/2012 à 18:11
source utilisateur

voix
2

Ce Soluton fonctionne pour moi, notez la ligne S'IL VOUS PLAÎT

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

Vous pouvez modifier la valeur 160 pour le match travailler avec vous

- (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];
}
Créé 02/12/2011 à 19:28
source utilisateur

voix
2

Puisque vous avez textfields dans une table, la meilleure façon est vraiment redimensionner la table - vous devez définir le tableView.frame être plus petit en hauteur par la taille du clavier (je pense autour de 165 pixels), puis l'étendre à nouveau lorsque le clavier est rejeté.

Vous pouvez éventuellement désactiver également l'interaction utilisateur pour le tableView à ce moment-là et, si vous ne voulez pas le défilement de l'utilisateur.

Créé 28/02/2009 à 19:37
source utilisateur

voix
1

Petite variation avec Swift 4.2 ...

Sur mon UITableView j'avais plusieurs sections , mais je devais éviter l'effet d' en- tête flottant donc j'utilisé un « dummyViewHeight approche » comme on le voit ailleurs ici sur Stack Overflow ... Voici donc ma solution pour ce problème (cela fonctionne aussi pour le clavier + suggestions barre d' outils de +):

Déclarer comme constante de classe:

let dummyViewHeight: CGFloat = 40.0

ensuite

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()
}

Et voilà toute la magie ...

@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)
    }
}
Créé 08/10/2018 à 10:45
source utilisateur

voix
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)];
        }







    }
Créé 12/02/2016 à 09:14
source utilisateur

voix
1

J'utilise ces derniers et ils travaillent comme un charme:

BSKeyboardControls - BSKeyboardControls github

TPKeyboardAvoiding - TPKeyboardAvoiding github

Créé 13/02/2014 à 09:30
source utilisateur

voix
1

J'utilise ce souvent dans mes projets. Cette solution fonctionne avec scrollviews, tableviews ou collectionviews et il est facile à installer. Il a également des crochets automatiquement des boutons « Suivant » sur le clavier pour passer à travers les champs de texte.

Vérifier ici

Créé 12/02/2014 à 21:27
source utilisateur

voix
1

Je vais jeter ma solution (ou QuickDialog de qui est) dans le chapeau. En fait attendre pour animer le défilement. Ce serait bien d'obtenir l'animation du clavier JIT au lieu du nombre magique.

-(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];
        });
    }
}
Créé 28/01/2014 à 19:05
source utilisateur

voix
1

Solution facile et rapide.

Je défilement juste à la cellule de droite à chaque fois que le défilement se produit

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView 

En supposant que je sais table est maintenant dans ce mode « _keepMyCellOnTop » et je sais que la cellule sélectionnée « _selectedCellIndex » ou faites défiler jusqu'à la cellule sélectionnée

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

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

Cela permettra d'éviter le défilement.

Placer le code -(void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView entraînera un défilement vers le haut et vers le bas

Créé 31/12/2013 à 13:37
source utilisateur

voix
1

Je viens après avoir résolu par moi-même un tel problème évoqué une masse de solutions trouvées via Google et Stack Overflow.

Tout d' abord, s'il vous plaît assurer que vous avez mis en place un IBOutlet de votre UIScrollView, alors s'il vous plaît jeter un oeil à portée d' Apple Doc: Gestion du clavier . Enfin, si vous pouvez faire défiler l'arrière - plan, mais le clavier couvre encore le champs de texte, s'il vous plaît jeter un oeil à ce morceau de code:

// 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 principale différence entre cette pièce et les mensonges d'Apple dans la condition if. Je crois que le calcul de la pomme de la distance de défilement et l'état si le champ texte couvert par le clavier ne sont pas exactes, donc je fait ma modification comme ci-dessus.

Laissez-moi savoir si cela fonctionne

Créé 18/08/2012 à 11:10
source utilisateur

voix
1

Voici comment je fait ce travail, qui est un mélange de Sam Ho et les réponses de Marcel W, et certains de mes propres corrections de bugs apportées à mon code de merde. Je travaillais avec un UITableViewController. Le tableau redimensionne maintenant correctement lorsque le clavier est affiché.

1) viewDidLoadJ'ajouté:

self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

2) J'avais oublié d'appeler les superéquivalents dans viewWillAppearet awakeFromNib. J'ai ajouté ces avant.

Créé 26/07/2012 à 18:18
source utilisateur

voix
1

Si votre UITableView est géré par une sous-classe de UITableViewController et non UITableView, et le délégué du champ de texte est le UITableViewController, il doit gérer tout le défilement automatique - sont très difficiles à mettre en œuvre dans la pratique tous ces commentaires.

Pour un bon exemple voir le projet de code exemple de pomme: TaggedLocations.

Vous pouvez voir qu'il défile automatiquement, mais il ne semble pas être un code qui fait cela. Ce projet a également des cellules de vue de table personnalisé, donc si vous construisez votre application avec comme guide, vous devriez obtenir le résultat souhaité.

Créé 05/03/2012 à 07:09
source utilisateur

voix
1

Une autre méthode facile (fonctionne uniquement avec une section)

//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];
Créé 23/11/2011 à 17:25
source utilisateur

voix
1

Donc , après les heures de travail épuisante essayer d'utiliser ces solutions actuelles (et tout à fait défaut) j'ai finalement obtenu les choses fonctionnent bien, et les mises à jour en les nouveaux blocs d'animation. Ma réponse est entièrement basée sur la réponse de Ortwin ci - dessus .

Donc, pour une raison quelconque le code a été ci-dessus fonctionne tout simplement pas pour moi. Ma configuration semblait assez similaire à d'autres, mais peut-être parce que je suis sur un iPad ou 4.3 ... aucune idée. Il faisait un peu de maths loufoque et le tir mon tableview hors de l'écran.

Voir résultat final de ma solution: http://screencast.com/t/hjBCuRrPC (S'il vous plaît ignorer la photo :-P).

Je suis donc allé avec l'essentiel de ce que Ortwin faisait, mais on a changé la façon dont il faisait un peu de mathématiques pour ajouter le origin.y & size.height de mon point de vue de la table à la hauteur du clavier. Quand je Soustraire la hauteur de la fenêtre de ce résultat, il me dit à quel point je intersection en cours. Si son supérieur à 0 (alias il y a un certain chevauchement) Je réalise l'animation de la hauteur du cadre.

De plus il y avait des questions qui ont été redessiner résolus par 1) d'attente pour accéder à la cellule jusqu'à ce que l'animation a été réalisée et 2) en utilisant l'option UIViewAnimationOptionBeginFromCurrentState en se cachant le clavier.

Un couple de choses à noter.

  • _topmostRowBeforeKeyboardWasShown & _originalFrame sont variables d'instance déclarées dans l'en-tête.
  • self.guestEntryTableView est mon tableView (je suis dans un fichier externe)
  • IASKCGRectSwap est la méthode de retournement Ortwin pour les coordonnées d'un cadre
  • Mettre à jour que la hauteur du tableView si au moins 50px de celui-ci va être montrant
  • Depuis que je ne suis pas dans un UIViewController Je n'ai pas self.view, donc je reviens juste le tableView à son cadre d'origine

Encore une fois, je ne l'aurais pas eu près de cette réponse si je Ortwin n'a pas fourni l'essentiel de celui-ci. Voici le code:

- (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;
}
Créé 18/07/2011 à 09:45
source utilisateur

voix
1

J'ai essayé presque la même approche et est venu avec un code plus simple et plus petit pour le même. J'ai créé un IBOutlet iTextView et associé à l'UITextView dans l'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];

    }
Créé 13/05/2011 à 06:00
source utilisateur

voix
1

Cela fonctionne parfaitement, et sur iPad aussi.

- (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];
        }
Créé 23/10/2010 à 08:11
source utilisateur

voix
0

Je viens de découvrir un autre bug lors de l'utilisation UITableViewController. Il n'a pas été défilant automatiquement lorsque le clavier est apparu. J'ai remarqué qu'il était à cause de contentInsetAdjustmentBehavior = .Ne sur UITableView.

Créé 03/07/2019 à 21:30
source utilisateur

voix
0

Solution pour Swift 3-4 avec des animations et changement du cadre du clavier:

Tout d'abord, créez un Bool:

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

En second lieu, ajouter des observateurs aux notifications de clavier du système:

// 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 troisième lieu, préparer la fonction d'animation:

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)
}

Ensuite, ajoutez les méthodes cible / action (appelé par les observateurs):

// 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)
        }
    }
}

Enfin, ne pas oublier de retirer les observateurs en deinit ou viewWillDisappear:

deinit {
    NotificationCenter.default.removeObserver(self)
}
Créé 10/06/2018 à 15:48
source utilisateur

voix
0

Pas besoin de calculs, utilisez le code ci-dessous il fonctionnera: Ce code je dans mon UITableViewCell personnalisé, il fonctionne:

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)
}}
Créé 22/02/2018 à 07:47
source utilisateur

voix
0

Swift 4 solution complète:

  • fonctionne correctement avec les changements de cadre de clavier (par exemple, la hauteur du clavier change comme emojii → clavier normal).
  • soutien TabBar et ToolBar par exemple UITableView (à d'autres exemples que vous recevez incorrectes encarts).
  • durée de l'animation dynamique (non codé en dur).
  • axé sur le protocole, de sorte que vous pouvez facilement l'utiliser dans toutes les situations.
  • Scroll fonctionne aussi empiècements.

J'ai écrit protocole d'aide (vous pouvez le télécharger comme essentiel , parce qu'il est trop grand pour poster sur StackOverflow), de sorte que votre point de vue juste besoin:

  1. Adopter le KeyboardChangeFrameObserverprotocole:

    func willChangeKeyboardFrame(height: CGFloat, animationDuration: TimeInterval, animationOptions: UIViewAnimationOptions)
    
  2. Appel observeKeyboardFrameChanges()à apparaître.

Exemple la mise en œuvre de ce protocole pour 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
        })
    }

}
Créé 12/01/2018 à 00:10
source utilisateur

voix
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];
Créé 27/06/2017 à 21:12
source utilisateur

voix
0

Regardez ma version :)

    - (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];
}
Créé 02/07/2016 à 20:32
source utilisateur

voix
0

Voici ma solution inspirée par l'écran « Event Edit » de l'application du calendrier iOS 7.

L'un des points clés de cette solution est que le clavier est rejeté lorsque la table de l'utilisateur fait défiler.

La mise en oeuvre:

1) Ajouter une propriété qui stockera textfield sélectionné:

@property (strong) UITextField *currentTextField;

et variable BOOL que nous utiliserons pour vérifier si nous avons besoin de cacher le clavier lorsque la table utilisateur fait défiler.

BOOL hideKeyboardOnScroll;

2) Poignée callbacks délégué 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) Procédé de poignée UIScrollViewDelegate pour vérifier ce point de vue de défilement de l'utilisateur.

#pragma mark - UIScrollViewDelegate

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

4) S'abonner aux notifications de clavier dans la méthode de viewcontroller [viewWillAppear] et résilier votre abonnement dans la méthode [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) traiter les notifications de clavier:

- (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;
}
Créé 21/08/2014 à 15:43
source utilisateur

voix
0

Je pense que la meilleure façon est par UITableViewController.

Si vous voulez un UITableView dans un UIViewController , juste faire un ContentView avec un UITableViewController intégré et de mettre les lignes suivantes dans le viedDidLoad du UIViewController:

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

Facile ;)

Créé 06/06/2014 à 16:29
source utilisateur

voix
0

Je pense qu'il n'y a aucun moyen « droit » de le faire. Vous devez choisir la meilleure solution adapté à votre cas d'utilisation. Dans mon App iPad J'ai un UIViewControllerqui est présenté modal UIModalPresentationFormSheetet consiste en un UITableView. Ce tableau contient deux UITextFieldspar cellule. Il suffit d' appeler scrollToRowAtIndexPath:atScrollPosition:animated:la textFieldDidBeginEditing:méthode ne fonctionne pas pour moi. Par conséquent , j'ai créé un 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];
}

L'idée est que le clavier se cache le tableFooterViewet non la UITextFields. Ainsi , le tableFooterViewdoit être suffisamment élevée. Après cela , vous pouvez utiliser scrollToRowAtIndexPath:atScrollPosition:animated:dans la textFieldDidBeginEditing:méthode.

Je pense qu'il est également possible de montrer et cacher la tableFooterViewdynamique en ajoutant les observateurs pour les notifications de clavier , mais je n'ai pas encore essayé:

- (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];
}
Créé 15/09/2012 à 08:51
source utilisateur

voix
0

J'ai créé un petit projet qui permet de résoudre ce problème avec le clavier, dans mon cas, je ne dois faire le point de vue de la table aller lorsque le clavier apparaît.

J'espère que cela t'aides!

http://git.io/BrH9eQ

Créé 19/11/2011 à 21:21
source utilisateur

voix
0

Je viens de regarder à nouveau dans la référence lib iOS 5.0 et trouvé cette section intitulée « Contenu mobile qui est situé sous le clavier »: TextAndWebiPhoneOS KeyboardManagement

Est-ce nouveau depuis iOS 5, peut-être? Je ne l'ai pas lu en encore que je suis au milieu de quelque chose d'autre, mais peut-être d'autres en savoir plus et me éclairer et d'autres ici.

Le doc d'Apple remplace ce qui a été discuté ici est l'information ici encore utile pour iOS 5 utilisateurs SDK?

Créé 26/10/2011 à 12:07
source utilisateur

voix
0

UITableViewControllerle fait automatiquement Scrolling, en effet. La différence par rapport à l' aide d' un UIViewControllerest que vous devez créer programme Navbar-Buttonitems en utilisant le NavigationController, lorsque vous utilisez un TableViewController.

Créé 20/03/2011 à 20:59
source utilisateur

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