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

前端 未结 3 570
我在风中等你
我在风中等你 2020-12-29 08:21

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\"

相关标签:
3条回答
  • 2020-12-29 08:55

    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) }
        }
    }
    
    0 讨论(0)
  • 2020-12-29 09:05

    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)
    
    }
    
    0 讨论(0)
  • 2020-12-29 09:13

    You can filter your visibleCells array to check if the frame of your cell is included in the frame of your collectionView:

        var visibleCells = self.collectionView?.visibleCells
        visibleCells = visibleCells?.filter({ cell -> Bool in
            return self.collectionView?.frame.contains(cell.frame) ?? false
        })
        print (visibleCells)
    
    0 讨论(0)
提交回复
热议问题