2017-10-19 58 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)