Search code examples
iosswiftxcodeuicollectionviewuiscrollview

Collection view doesn't clip to the edges of the view when scrolling and dismissing


I have a UICollectionView and my problem is that if I'm dismissing the view controller which contains the collection view while a collection view scroll is still in progress, the collection view doesn't get clipped to the edge of the view and I can see the cells that are outside the view's bounds while the view controller is being dismissed.

I'm using collection view flow layout, here is my code:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let flow = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    
    let height = collectionView.frame.height - flow.sectionInset.top - flow.sectionInset.bottom
    let size = CGSize(width: cellWidth, height: height)
    return size
}

I also manipulate the scroll process with the following code, so the scrolling stops at the specified point each time:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
  
    let width: CGFloat = cellWidth + cellOffset
    let xOffset = scrollView.contentOffset.x
    let page: Double = Double(xOffset / width)
    var pageInt: Int = Int(page.round(to: 0))
    
    if velocity != .zero {
        pageInt = velocity.x > 0 ? pageInt+1 : pageInt-1
    }
    
    let newXOffset = CGFloat(pageInt) * width
    let point = CGPoint(x: newXOffset, y: 0)
    targetContentOffset.pointee = point
}

Solution

  • So I figured out my stupid mistake almost instantly after posting the question. I applied a shadow to my collection view's layer and set its masksToBounds to false. Setting masksToBounds to true resolved it.