Prevent UITableView from scrolling to a cell containing textField

UITableView seems to have some automatic behavior when a cell contains a text element or a text element, and this field or view becomes the first responder, tableView scrolls so that the cell is not covered by the keyboard. I am sure that in most cases it is very convenient.

In my case, this is not good. The TableView is inside a smaller container, and by default the behavior of the field remains private. I want to handle moving the entire container myself, and the default scroll behavior interferes.

Does anyone know how I can disable this UITableView feature?

+7
source share
2 answers

I had the same problem, I had a UITableView in the smaller container view, and when I selected the UITextField in the tableView, it would automatically scroll to an undesirable position. This is the default behavior for a UITableView and there is no way to disable it.

Instead, I changed this subView controller to a subclass of UIViewController instead of UITableViewController. ie for my TransportViewController.h that controls tableView:

@interface TransportViewController : UITableViewController <UITextFieldDelegate> 

become:

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

By setting the class as the UIViewController class, automatic scrolling of table cells will not occur.

Now that you are not subclassing the UITableViewController, you must manually set the tableView property to indicate the appropriate type of table. You can link this in IB, which will give you something like:

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

Finally, you will also need to set this newly assigned tableView property as the delegate and table data source. You can do this in the 'viewDidLoad' method as follows:

 - (void)viewDidLoad { [super viewDidLoad]; _tableView.dataSource = self; _tableView.delegate = self; } 

This will stop the automatic scrolling that is inherent in the UITableViewController when selecting a UITextField. Then you need to implement any necessary UITableViewDataSource methods and process your own auto scroll methods.

+1
source

I solved this by implementing the scrollViewDidScroll: method (from the UIScrollViewDelegate protocol). This method is called when the keyboard scrolls a UITableView .

Here is what I did:

 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [tableViewController.tableView setContentOffset:CGPointMake(0., 0.)]; } 
0
source

All Articles