Making a UITableView scroll when text field is selected Making a UITableView scroll when text field is selected ios ios

Making a UITableView scroll when text field is selected


If you use UITableViewController instead of UIViewController, it will automatically do so.


The function that does the scrolling could be much simpler:

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

That's it. No calculations at all.


I'm doing something very similar it's generic, no need to compute something specific for your code.Just check the remarks on the code:

In 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

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