Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine when a custom UICollectionViewCell is 100% on the screen

Tags:

enter image description here

From the diagram above I have UICollectionView with 4 custom cells. At any time 2 or three cells can be on the screen. How can I tell when "cell 1" or "cell 2" is 100% on the screen?

Both

collectionView.visibleCells
collectionView.indexPathsForVisibleItems

return arrays and doesn't tell you if what cell 100% on the screen.

In the case of the image, the following will be display on didSelectItemAt

collectionView.visibleCells

[<Shot_On_Goal.MainCollectionViewCell: 0x101f525c0; baseClass = UICollectionViewCell; frame = (190 7.66667; 454 350); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x1c0237300>>, <Shot_On_Goal.HeaderCollectionViewCell: 0x101f4d580; baseClass = UICollectionViewCell; frame = (10 0; 170 365); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x1c0236800>>, <Shot_On_Goal.TheirHockeyNetCollectionViewCell: 0x101f55520; baseClass = UICollectionViewCell; frame = (654 7.66667; 454 350); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x1c0238fe0>>]

collectionView.indexPathsForVisibleItems

[[0, 1], [0, 0], [0, 2]] 
like image 959
Paul S. Avatar asked Oct 19 '17 12:10

Paul S.


2 Answers

This will return an Array of IndexPaths for the fully visible cells:

func fullyVisibleCells(_ inCollectionView: UICollectionView) -> [IndexPath] {

    var returnCells = [IndexPath]()

    var vCells = inCollectionView.visibleCells
    vCells = vCells.filter({ cell -> Bool in
        let cellRect = inCollectionView.convert(cell.frame, to: inCollectionView.superview)
        return inCollectionView.frame.contains(cellRect) 
    })

    vCells.forEach({
        if let pth = inCollectionView.indexPath(for: $0) {
            returnCells.append(pth)
        }
    })

    return returnCells

}

@IBAction func test(_ sender: Any) {

    let visCells = fullyVisibleCells(self.collectionView)
    print(visCells)

}
like image 148
DonMag Avatar answered Sep 23 '22 05:09

DonMag


Here's an extension for it, based don DonMag's answer:

extension UICollectionView {
    var fullyVisibleCells : [UICollectionViewCell] {
        return self.visibleCells.filter { cell in
            let cellRect = self.convert(cell.frame, to: self.superview)
            return self.frame.contains(cellRect) }
    }
}
like image 39
Lio Avatar answered Sep 22 '22 05:09

Lio