如何判断UITableViewCell的可见程度

AJ.*_*AJ. 4 uitableview ios

UITableView具有确定当前可见的单元格的方法.我想要找出的是一个细胞有多少是可见的.

例如,当您向下拖动表格时,表格顶部的"新显示"单元格不会出现,而是一次显示一条(像素)线,直到整个单元格可见.当拖动表格视图时,如何判断在任何给定时刻该单元格的可见程度.

我的最终目标是,当用户拖动桌面时,根据在任何给定时间可见的多少来更改单元格内的显示视图.

有什么建议?

Cat*_*lin 6

你可以尝试这样的事情:

-(void)scrollViewDidScroll:(UIScrollView *)sender
{
    [self checkWhichVideoToEnable];
}

-(void)checkWhichVideoToEnable
{
    for(UITableViewCell *cell in [tblMessages visibleCells])
    {
        if([cell isKindOfClass:[VideoMessageCell class]])
        {
            NSIndexPath *indexPath = [tblMessages indexPathForCell:cell];
            CGRect cellRect = [tblMessages rectForRowAtIndexPath:indexPath];
            UIView *superview = tblMessages.superview;

            CGRect convertedRect=[tblMessages convertRect:cellRect toView:superview];
            CGRect intersect = CGRectIntersection(tblMessages.frame, convertedRect);
            float visibleHeight = CGRectGetHeight(intersect);

            if(visibleHeight>VIDEO_CELL_SIZE*0.6) // only if 60% of the cell is visible
            {
                // unmute the video if we can see at least half of the cell
                [((VideoMessageCell*)cell) muteVideo:!btnMuteVideos.selected];
            }
            else
            {
                // mute the other video cells that are not visible
                [((VideoMessageCell*)cell) muteVideo:YES];
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Max*_*eod 5

这是以上在Swift中实现的变体:

    var cellRect = tableView.rectForRowAtIndexPath(indexPath)
    if let superview = tableView.superview {
        let convertedRect = tableView.convertRect(cellRect, toView:superview)
        let intersect = CGRectIntersection(tableView.frame, convertedRect)
        let visibleHeight = CGRectGetHeight(intersect)
    }
Run Code Online (Sandbox Code Playgroud)

visibleHeight是单元格中可见的部分。可以再增加一个步骤来计算可见单元格的比率(介于零和一之间):

    var cellRect = tableView.rectForRowAtIndexPath(indexPath)
    if let superview = tableView.superview {
        let convertedRect = tableView.convertRect(cellRect, toView:superview)
        let intersect = CGRectIntersection(tableView.frame, convertedRect)
        let visibleHeight = CGRectGetHeight(intersect)
        let cellHeight = CGRectGetHeight(cellRect)
        let ratio = visibleHeight / cellHeight
    }
Run Code Online (Sandbox Code Playgroud)

要根据可见性更改视图外观(如上面的问题所述),此代码应包括在表视图的UIScrollView超类委托UIScrollViewDelegate方法scrollViewDidScroll中

但是,这只会影响单元格滚动时的状态。已经可见的单元格将不受影响。对于这些,应该在UITableViewDelegate方法didEndDisplayingCell中应用相同的代码。


bsh*_*ley 4

我还没有测试过,但我会尝试以下方法:

UITableViewCell *cell;
UIView *parent = cell.superview;
CGRect overlap = CGRectIntersection(cell.frame, parent.bounds);
Run Code Online (Sandbox Code Playgroud)

然后比较特定的矩形。