从UITableView pagingEnabled获取可见单元格

4th*_*ace 16 iphone cocoa-touch uitableview

我有一个带有pagingEnabled的UITableView.每个单元占据桌子的观察区域.意思是,每个单元格与表格的高度和宽度相同.我正在使用具有name属性的自定义单元格.我想在标签中显示当前(可查看)单元格的名称.这适用于第一个和最后一个单元格,但中间的任何内容都不是那么容易.问题是为这些中间单元调用了两次cellForRowAtIndexPath.这是从第一个单元格滚动到最后一个单元格然后返回的样子.我已按顺序列出索引,因为cellForRowAtIndexPath会触发该行:

Row             indexPath.row
 0                   0         //view loads and table appears
 1                  1,2        //user scrolls to second cell. cellForRowAtIndexPath fires twice.  First time indexPath.row is one and second time it is two.  This causes cell two's name to display in the label, rather than cell one.
 2                  2,3
 3                   3
 //user starts scrolling back to first cell
 2                  1,2 
 1                  1,0
 0                   0
Run Code Online (Sandbox Code Playgroud)

我可以设置使用NSDate对象来检测我是否在中间行.通过将当前时间与当前时间进行区分,我知道.但是,如果用户在单元格中快速滚动,则可能不起作用.还有另一种方法吗?

我尝试过使用visiblecells属性的变体但是没有用.UITableView将加载下一个单元格,即使它不可见,也会导致它成为可见单元格的一部分.

Dou*_*yle 44

好吧,如果您没有找到解决方案的机会,或者接下来遇到这个问题的人,我会向您提供您正在寻找的答案.UITableView将为您提供您正在寻找的indexPath,然后UITableView将很乐意为您提供与这些索引路径匹配的单元格:

UITableView *tableView = self.tableView; // Or however you get your table view
NSArray *paths = [tableView indexPathsForVisibleRows];

//  For getting the cells themselves
NSMutableSet *visibleCells = [[NSMutableSet alloc] init];

for (NSIndexPath *path in paths) {
    [visibleCells addObject:[tableView cellForRowAtIndexPath:path]];
}

// Now visibleCells contains all of the cells you care about.
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用[tableView visibleCells]获取可见单元格; (21认同)