Search code examples
iosuitableviewscrollcell

Scroll custom UITableViewCell to right above keyboard?


Currently I have a UITableView with custom cells and in each cell there is a UITextField, the problem is that sometimes the UITextField is covered by the UIKeyboard.

So right now I have the Y coordinate for the UIKeyboard and my UITableView is functioning properly with the cells.

So pretty much how can I use that Y coordinate (float), in order to scroll my UITableView to that Y coordinate plus the height of the cell in order to get it right above my UIKeyboard?

Also when I the keyboard hides, how would I reset the UITableView to its normal position that it was in?

Any advice would be appreciated!

Thanks!

CustomCell *cell = (CustomCell*)[[thetextField superview] superview];
    CGRect cellRect = [cell convertRect:cell.frame toView:self.view];
    float bottomCell = cellRect.origin.y - cellRect.size.height;
    if (bottomCell >= keyboardY) {
        NSIndexPath *indexPath = [thetableView indexPathForCell:cell];
        [thetableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }

Solution

  • One or the other of UITableView's

    - (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;
    - (void)scrollToNearestSelectedRowAtScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;
    

    I'm guessing that control isn't getting into the if statement. Consider skipping the y-coordinate check in favor of just scrolling the table view regardless of where it is.

    CustomCell *cell = (CustomCell *)[[theTextField superview] superview];
    NSIndexPath *indexPath = [theTableView indexPathForCell:cell];
    [theTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    

    OK, if you're sure it's getting called, then make sure your indexPath isn't nil, which may happen if cell isn't in the tableView or if it's not a cell.