Reputation: 19737
I have a UITableView
with a few UITableViewCell
s. Each cell contains a UITextfield
. Tapping the textFields causes the keyboard to display. Unfortunately the keyboard covers some of the cells that are lower on the iPhone's screen.
What's the easiest way to scroll the tableView up when the keyboard is displayed?
I've experimented with the contentOffset
. This works for actually scrolling the tableView. However I'm having trouble determining which cell is "active" (has a textField that's currently the firstResponder). My app supports both portrait and landscape orientation so the tableView sometimes needs to be scrolled when the device rotates.
Upvotes: 0
Views: 1442
Reputation: 1007
I am writing an app that has a similar issue. The way that I am handling keeping track of the first responder, or active UITextField, is by using a callback. I call a method using the UIControlEvent UIControlEventEditingDidBegin.
Where I setup the UITextField:
[self.nameUnitNumberField addTarget:self.textFieldDelegate action:@selector(handleEditingDidBegin:) forControlEvents:UIControlEventEditingDidBegin];
Then in the delegate class, I set the current text field:
- (void)handleEditingDidBegin:(id)sender
{
self.currentNameField = (UITextField *)sender;
}
This seems to be working well. It also avoids the use of tags. I've heard that there are potential problems with it and it's best to avoid it when not needed.
Once you have the active UITextField, you can use either the contentInset and scrollToRowAtIndex: as described here: Get UITableView to scroll to the selected UITextField and Avoid Being Hidden by Keyboard
or just resize the table view while the keyboard is on screen. That would be simplest way to do it.
Upvotes: 1
Reputation: 868
A simple way to keep track of which textField is currently active is to set its tag
property to the indexPath's row on cellForRowAtIndexPath:
Another way is to use this line:
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:[textField convertPoint:textField.frame.origin toView:self.tableView]];
on textFieldShouldBeginEditing:
for when the textField becomes active, or on your rotation callbacks for when the device rotates, and then scroll the tableView using scrollToRowAtIndexPath:atScrollPosition:animated:
Upvotes: 2