为什么我的UITableView不能滚动到正确的索引行?
问题描述:
我是一个UITableView设置并加载了大约3条记录。 Interface Builder中UITableView的高度仅为44像素。每行的高度设置为44像素。为什么我的UITableView不能滚动到正确的索引行?
这意味着一次只能看到一行,但可以拖动并滚动到新行。我想UITableView也总是显示滚动到最可见的行。
我已经安装了下面的代码:
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
// Get the center of the UITableView bounds
CGPoint tableViewCenter = self.activeTableView.center;
// Get the row that is currently occupying the center point in the UITableView
NSIndexPath *row = [self.activeTableView indexPathForRowAtPoint:CGPointMake(tableViewCenter.x, tableViewCenter.y)];
// Animate and scroll to this row making it the only visible row.
[self.activeTableView scrollToRowAtIndexPath:row atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
我的问题是,无论我做什么,它总是滚动回于1行的记录。我可以一直拖到第三排,然后放手,并一直滚动回到第一条记录?如果在我放手之后它是最显眼的行,它不应该滚动并居中第3行吗?
谢谢!
答
你的问题是,当你滚动tableView.center不会改变。只有当你改变tableview的框架时,中心才会改变。
你应该使用的是UIScrollView的contentOffset。
与此更换你的tableViewCenter代码,它应该工作
CGPoint tableViewCenter = scrollView.contentOffset;
// contentOffset is the position of the first visible pixel in the upper left corner
// add half the height so the relevant point is in the middle of the tableView
tableViewCenter.y += self. activeTableView.frame.size.height/2;