Disabling automatic scrolling of UITableView when editing UITextField inside UITableViewCell

I'm using custom UITableViewCells inside my UITableView. Each of these UITableViewCells is pretty high and contains a UITextField at the top.

When a user taps the UITextField in order to edit it, a keyboard appears and the UITableView scrolls automatically so that the cell is at the top of the screen.

The problem is that this scrolls the UITableView to the bottom of the UITableViewCell, not the top. When the UITableViewCell is high and edited the UITextField is at the top so you can't see the UITextField. I know how to scroll the UITableView programmatically, but I just don't know how to disable this automatic scrolling so that I can scroll the UITableView on my own. How can I do this?


Solution 1:

The autoscroll-behavior is located in the UITableViewController functionality.

To disable the automatic scrolling I found two ways:

  1. Use instead of the UITableViewController simply a UIViewController - set the datasource and delegate on your own.
  2. Override the viewWillAppear method and don't call [super viewWillAppear: animated]

With both solution you disable not only the Autoscroll, but also some other nice but not essential features, that are described in the overview of Apple´s class reference:

https://developer.apple.com/documentation/uikit/uitableviewcontroller

Solution 2:

Define properties for your UITableViewController:

@property (nonatomic) BOOL scrollDisabled;
@property (nonatomic) CGFloat lastContentOffsetY;

Before you call becomeFirstResponder:

// Save the table view's y content offset 
lastContentOffsetY = tableViewController.tableView.contentOffset.y;
// Enable scrollDisabled
scrollDisabled = YES;

Add the following code to your table view controller:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.scrollDisabled) {
        [self.tableView setContentOffset:CGPointMake(0, lastContentOffsetY)];
    }
    ...
}

After you call resignFirstResponder, set scrollDisabled = NO.