如何解决计算UITableView将在哪一行停止滚动?
| 当一个表有很多行时,用户可以向上/向下滑动表。这将创建一个滚动动画,该动画似乎具有确定的长度,具体取决于轻拂手势的速度/长度。如果没有进一步的用户交互,一旦滚动停止,是否可以可靠地计算出表格中的哪些行将可见?解决方法
在iOS 5.0及更高版本中,UIScrollViewDelegate有一个新的API,称为scrollViewWillEndDragging:withVelocity:targetContentOffset:。使用这种新方法,可以计算出滚动的停止位置,甚至可以修改滚动的停止位置,如视频会议100:第九分钟左右的“可可触摸中的新增功能”中所述。
,
UITableView
继承自UIScrollView
,可以通过使用UIScrollViewDelegate
方法和表视图indexPathsForVisibleRows
属性来检查滚动停止时哪些单元格索引路径可见,从而实现此目的。
您甚至可以保存减速开始的初始位置,以便可以计算滚动方向是向上还是向下,这将让您知道要停止的单元格是可见的第一个还是最后一个那些。
int startDeceleratingPosition;
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
startDeceleratingPosition = scrollView.contentOffset.y;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
BOOL isPositionUp = startDeceleratingPosition < scrollView.contentOffset.y;
NSArray *paths = [_myTableview indexPathsForVisibleRows];
UITableViewCell *cell;
if(isPositionUp){
cell = [_myTableview cellForRowAtIndexPath:[paths objectAtIndex:0]];
} else {
cell = [_myTableview cellForRowAtIndexPath:[paths lastObject]];
}
}
关于上面的代码的重要说明是,它指向表视图时是变量_myTableview
,而不只是将委托方法变量scrollView
转换为UITableView *
,尽管这只是实现细节,不应影响此处的逻辑。
,有趣的问题.....UITableViewDelegate
也符合UIScrollViewDelegate
:http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScrollViewDelegate_Protocol/Reference/UIScrollViewDelegate.html#//apple_ref/occ/intf / UIScrollViewDelegate
您可以使用一些委托回调来了解滚动何时开始减速,何时结束减速。
您可能使用ѭ10,然后使用tableView的像元高度和内容偏移属性(tableView子类UIScrollView
),然后计算减速后可见的像元。
,我不知道如何确定将显示多少行,但是您总是可以得到已显示多少行。 (一旦桌子停下来,不再有进一步的接触。)
不确定是否有帮助,但这就是您的做法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// make sure to declare your integer in your .h file and to also synthesize
//say this is your int \"howManyRowsAreShowing\"
howManyRowsAreShowing = indexPath.Row;
//the rest of the code below is generic table view code for example only
static NSString *CellIdentifier = @\"Cell\";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
NSString *cellValue = [listOfItems objectAtIndex:indexPath.row];
cell.text = cellValue;
return cell;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。