滚动和关闭时,集合视图不会裁剪到视图的边缘

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

我有一个 UICollectionView,我的问题是,如果我关闭包含集合视图的视图控制器,而集合视图滚动仍在进行中,则集合视图不会被裁剪到视图的边缘,当视图控制器被关闭时,我可以看到视图边界之外的单元格。

我正在使用集合视图流布局,这是我的代码:

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
}

我也是用下面的代码来操作滚动过程,所以每次都在指定的点停止滚动:

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
}

所以我在发布问题后几乎立刻就发现了我的愚蠢错误。我将阴影应用到我的集合视图层并将其 masksToBounds 设置为 false。将 masksToBounds 设置为 true 解决了它。