强制UITableView滚动到单元格顶部 [英] Force UITableView to Scroll to Tops of Cells
问题描述
有没有办法让UITableViews滚动单元格到单元格?也就是说,表视图的顶部始终是UITableViewCell的顶部。
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 that seems to scroll whole "pages." I just want cell to cell scrolling.
谢谢
推荐答案
UTTableView
是 UIScrollView
的子类,因此您可以使用 scrollViewDidScroll
滚动后重新排列TableView滚动位置的方法。
UTTableView
is a subclass of UIScrollView
, so you can use scrollViewDidScroll
method to rearrange your TableView scroll position after scroll.
您可以使用 tableView.contentOffset
来获取当前的位置滚动位置。通过将其划分为有意义的数字,您可以获得最顶层的单元格。
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];
您可以使用 UIScrollViewDelegate
方法激活捕捉。您可以在滚动动画完成时或动画仍在继续时激活。这将产生不同的用户交互,并且不能说一个比另一个更好。
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));
}
当用户触及 TableView时会调用此方法
通知申请。 targetContentOffset
是一个 inout
变量,因此您可以在动画继续时实际设置最终滚动位置。使用右 cellHeight
,您的 TableView
将始终捕捉到单元格。
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.
这篇关于强制UITableView滚动到单元格顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!