2017-10-19 49 views
4

enter image description here如何确定当定制UICollectionViewCell是屏幕

从图上100%以上我有UICollectionView用4个定制单元。在任何时候,可以在屏幕上显示2或3个单元格。如何知道屏幕上的“单元格1”或“单元格2”是否为100%?

两个

collectionView.visibleCells 
collectionView.indexPathsForVisibleItems 

返回队列,不告诉你,如果在屏幕上什么细胞100%。

在图像的情况下,以下将显示器上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]] 
+0

你有没有考虑过使用[CGRectContainsRect(https://developer.apple.com/documentation/coregraphics/1454186-cgrectcontainsrect) ? – Wez

+0

看起来像有人用[tableViewCell](https://stackoverflow.com/questions/9831485/best-way-to-check-if-uitableviewcell-is-completely-visible)这样做了。 – Wez

回答

4

这将返回IndexPaths的数组中完全可见的细胞:

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

感谢您的解决方案,效果很好。 –

1

可以筛选visibleCells阵列,以检查是否的帧您的手机包含在您收藏的相框中:

var visibleCells = self.collectionView?.visibleCells 
    visibleCells = visibleCells?.filter({ cell -> Bool in 
     return self.collectionView?.frame.contains(cell.frame) ?? false 
    }) 
    print (visibleCells)