Search code examples
iosobjective-cuitableviewuiscrollviewdelegate

Want UITableView to "snap to cell"


I am displaying fairly large images in a UITableView. As the user scrolls, I'd like to the table view to always snap the center-most photo in the middle. That is, when the table is in a resting state, it will always have a UITableViewCell snapped to the center.

How does one do this?


Solution

  • You can use the UIScrollViewDelegate methods on UITableView to do this:

    - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
        // if decelerating, let scrollViewDidEndDecelerating: handle it
        if (decelerate == NO) {
            [self centerTable];
        }
    }
    
    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
        [self centerTable];
    }
    
    - (void)centerTable {
        NSIndexPath *pathForCenterCell = [self.tableView indexPathForRowAtPoint:CGPointMake(CGRectGetMidX(self.tableView.bounds), CGRectGetMidY(self.tableView.bounds))];
    
        [self.tableView scrollToRowAtIndexPath:pathForCenterCell atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }