带有一个可见单元格的 UITableView:确定哪个单元格最可见 [英] UITableView with one visible cell: determine which is most visible
问题描述
给定一个在任何给定时间带有单个可见单元格的 UITableView,如何在滚动表格视图时确定哪个单元格最?
Given a UITableView with a single visible cell at any given time, how can I determine which cell is most in view while the table view is being scrolled?
我知道我可以通过这样做获得一组可见的单元格:
I know I can get an array of visible cells by doing this:
NSArray *paths = [tableView indexPathsForVisibleRows];
然后通过执行以下操作获取最后一个单元格(或第一个,或其他):
And then get the last cell (or first, or whatever) by doing:
UITableViewCell* cell = (UITableViewCell*)[tableView cellForRowAtIndexPath:[paths lastObject]];
但是如何比较所有可见的单元格并确定它们中的哪一个最能看到?
But how to I compare all the visible cells and determine which of them is most in view?
推荐答案
算法根据返回的路径数而有所不同:
The algorithm is different depending on how many paths you get back:
- 如果只有一条路径,那就是那里最明显的单元格
- 如果存在三个或更多路径,则中间的任何单元格(即除第一个和最后一个单元格之外的所有单元格)同样可见
- 如果正好有两个单元格,则在它们的父视图中找到分隔这两个单元格的线的位置*,并计算两个距离 - 顶部到中间和中间到底部.如果从上到中更大,则顶部单元格最明显.如果中间到底部更大,则第二个单元格更明显.否则,两个单元格同样可见.
- If there is only one path, that's the most visible cell right there
- If there are three or more paths, any of the cells in the middle (i.e. all cells except the first and the last ones) are equally visible
- If there are exactly two cells, find the position of the line that separates the two in their parent view*, and compute two distances - top-to-middle and middle-to-bottom. If top-to-middle is greater, then the top cell is most visible. If middle-to-bottom is greater, then the second cell is more visible. Otherwise, the two cells are equally visible.
* 中点位置是第二个单元格的底部.顶部和底部位置是表格视图的顶部和底部.
* Midpoint position is the bottom of the second cell. Top and bottom positions are the top and bottom of the table view.
这篇关于带有一个可见单元格的 UITableView:确定哪个单元格最可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!