计算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;
    }
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...