Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell how much of a UITableViewCell is visible

UITableView has methods for determining which cells are currently visible. What I'm trying to find out is how much of a cell is visible.

For instance, as you drag a table down the 'newly visible' cell at the top of the table doens't just appear but appears a (pixel) line at a time until the whole cell is visible. How can I tell how much of that cell is visible at any given moment as the table view is dragged.

My final aim is, as the user drags on the table, to change the appearing view within the cell dependent on how much of it is visible at any given time.

Any suggestions?

like image 976
AJ. Avatar asked Feb 22 '12 04:02

AJ.


1 Answers

Here is a variation of the above implemented in 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)
    }

visibleHeight being the part of the cell that is visible. One further step can be added to calculate the ratio - between zero and one - of the cell that is visible:

    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
    }

To change view appearances depending on visibility - as the question states above - this code should be included in the table view's UIScrollView superclass delegate, UIScrollViewDelegate method scrollViewDidScroll.

However, that will only affect cells as they scroll. Cells already visible would not be affected. For those, the same code should be applied in the UITableViewDelegate method didEndDisplayingCell.

like image 94
Max MacLeod Avatar answered Oct 19 '22 05:10

Max MacLeod