Is there a way to make UITableViews scroll cell to cell? That is, the top of the Table View is always the top of a UITableViewCell.
I tried the pageation flag, but t
UTTableView
is a subclass of UIScrollView
, so you can use scrollViewDidScroll
method to rearrange your TableView scroll position after scroll.
You can use tableView.contentOffset
to get where is your current scroll position. And by dividing it to a meaningful number you can get which cell is on top.
int cellIndex = tableView.contentOffset / cellHegiht;
Or you can get currently visible cell on center (top, bottom) like this:
NSArray *indexPathsForVisibleRows = [tableView indexPathsForVisibleRows];
NSIndexPath *selectedIndexPath = [indexPathsForVisibleRows objectAtIndex:(indexPathsForVisibleRows.count / 2)]; //this gets center cell
After calculating which cell should be clicked by its edge on top (or bottom) you can correct the drift from cell edge by calling:
[tableView scrollToRowAtIndexPath:selectedIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
You can use UIScrollViewDelegate
methods to activate snapping. You can activate either when the scrolling animation completed or while the animation still continues. This will generate different user interaction and can't say one is better then another.
But just implementing following method and nothing else looks like going to be my favorite:
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
withVelocity:(CGPoint)velocity
targetContentOffset:(inout CGPoint *)targetContentOffset {
int cellHeight = 41;
*targetContentOffset = CGPointMake(targetContentOffset->x,
targetContentOffset->y - (((int)targetContentOffset->y) % cellHeight));
}
This method gets called when user touches up on TableView
to notify application. targetContentOffset
is an inout
variable so you can actually set final scroll position while animation is continuing. Using right cellHeight
, your TableView
will always snap to cells.