Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent UITableView from scrolling to cell containing textField

Tags:

objective-c

UITableView appears to have some automatic behaviour where, if a cell contains a textField or textView, and that field or view becomes first responder, the tableView scrolls itself so that the the cell is not obscured by the keyboard. I'm sure that, in most cases, this is very handy.

In my case it's no good. The tableView is within a smaller containerView, and the default behaviour leaves the field still obscured. I want to handle moving the whole container myself, and the default scrolling behaviour is getting in the way.

Does anyone know how I can "turn off" this feature of UITableView?

like image 775
James White Avatar asked Apr 21 '13 13:04

James White


Video Answer


1 Answers

I had this exact same problem, I had a UITableView in a smaller container view and when I selected a UITextField in the tableView it would auto-scroll to an undesirable position. This is the default behaviour of a UITableView and there doesn't appear to be any way to switch it off.

Instead, I changed this subView controller to be a subclass of a UIViewController instead of a UITableViewController. i.e for my TransportViewController.h which controls a tableView:

@interface TransportViewController : UITableViewController <UITextFieldDelegate>

became:

@interface TransportViewController : UIViewController <UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate>

By setting the class as a UIViewController class instead, the automatic scroll of the table cells will not happen.

Now that you are not subclassing UITableViewController you must now manually set the 'tableView' property to point to the appropriate table view. You can connect this in IB which will give you something like:

@property (strong, nonatomic) IBOutlet UITableView *tableView;

Finally you will also have to set this newly assigned tableView property to be the delegate and data source of the table. You can do this in the 'viewDidLoad' method like so:

- (void)viewDidLoad
{
    [super viewDidLoad];

    _tableView.dataSource = self;
    _tableView.delegate = self;

}

This will stop the auto scrolling that is inherent in the UITableViewController when a UITextField is selected. It is then up to you to implement any necessary UITableViewDataSource methods, and to handle your own auto-scrolling methods.

like image 142
Tys Avatar answered Oct 03 '22 15:10

Tys