检查UITableViewCell是否完全可见的最佳方法

105

我有一个UITableView,其中包含高度不同的单元格,并且我需要知道它们何时完全可见。

目前,每次视图滚动时,我都会循环遍历可见单元格列表中的每个单元格,以检查它是否完全可见。这是最佳方法吗?

这是我的代码:

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {

    CGPoint offset = aScrollView.contentOffset;
    CGRect bounds = aScrollView.bounds;    
    NSArray* cells = myTableView.visibleCells;

    for (MyCustomUITableViewCell* cell in cells) {

        if (cell.frame.origin.y > offset.y &&
            cell.frame.origin.y + cell.frame.size.height < offset.y + bounds.size.height) {

            [cell notifyCompletelyVisible];
        }
        else {

            [cell notifyNotCompletelyVisible];
        }
    }
}

编辑:

请注意,* - (NSArray )visibleCells 返回的是完全可见和部分可见的可见单元格。

编辑2:

在lnafziger和Vadim Yelagin的方案结合后,这是修改后的代码:

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
    NSArray* cells = myTableView.visibleCells;
    NSArray* indexPaths = myTableView.indexPathsForVisibleRows;

    NSUInteger cellCount = [cells count];

    if (cellCount == 0) return;

    // Check the visibility of the first cell
    [self checkVisibilityOfCell:[cells objectAtIndex:0] forIndexPath:[indexPaths objectAtIndex:0]];

    if (cellCount == 1) return;

    // Check the visibility of the last cell
    [self checkVisibilityOfCell:[cells lastObject] forIndexPath:[indexPaths lastObject]];

    if (cellCount == 2) return;

    // All of the rest of the cells are visible: Loop through the 2nd through n-1 cells
    for (NSUInteger i = 1; i < cellCount - 1; i++)
        [[cells objectAtIndex:i] notifyCellVisibleWithIsCompletelyVisible:YES];
}

- (void)checkVisibilityOfCell:(MultiQuestionTableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath {
    CGRect cellRect = [myTableView rectForRowAtIndexPath:indexPath];
    cellRect = [myTableView convertRect:cellRect toView:myTableView.superview];
    BOOL completelyVisible = CGRectContainsRect(myTableView.frame, cellRect);

    [cell notifyCellVisibleWithIsCompletelyVisible:completelyVisible];
}

3
作为一则旁注,您应该去查看之前所有的问题,并接受那些帮助过您的答案。 - Baub
4
谢谢告诉我!我已经给他们点了+1,但是忘记了设置采纳答案的功能。 - RohinNZ
你的代码看起来对我来说是正确的,虽然它很复杂,但它能够工作。不要修复没有问题的东西,好吗? - CodaFi
这是来自@matt的一篇非常棒的答案,还附带了一个动画 https://stackoverflow.com/a/68109661/4833705 - Lance Samaria
12个回答

0
- (BOOL)checkVisibilityOfCell{
    if (tableView.contentSize.height <= tableView.frame.size.height) {
        return YES;
    } else{
        return NO;
    }
}

0
由于某些原因,当我使用 tableView.rectForRowAtIndexPath(indexPath) 来获取 UITableViewCell 的框架时,高度为 0
最终我使用了以下方式:-
for cell in tableView.visibleCells {
    let cellFrame = cell.frame
    let completelyVisible = tableView.bounds.contains(cellFrame)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接