Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

iphone - Getting visible cell from UITableView pagingEnabled

I have a UITableView with pagingEnabled. Each cell takes up the viewing area of the table. Meaning, each cell is the same height and width as the table. I'm using custom cells that have a name property. I'd like to display the name of the current (viewable) cell in a label. This works fine for the first and last cells but anything inbetween isn't so easy. The problem is that cellForRowAtIndexPath is called twice for these middle cells. Here's what it looks like scrolling from the first to last cell and then back. I've listed the indexes in order as cellForRowAtIndexPath fires for that row:

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

I could set use an NSDate object to detect if I'm in a middle row. By diffing the previous time with current, I'll know. However, if the user scrolls really fast through the cells, that probably doesn't work. Is there another way to do it?

I've tried using variations of visiblecells properties but that didn't work. The UITableView will load the next cell even if it isn't visible, causing it to be part of the visible cells.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, on the off chance that you never figured out a solution, or for whoever comes to this question next, I'll provide you with the answer you were looking for. UITableView will provide you with the indexPaths you are looking for, and then UITableView will happily provide you with the cells that match those index paths:

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...