Swift CollectionView 垂直分页

mpa*_*h91 0 paging scrollview collectionview swift

我在我的集​​合视图上启用了分页,并遇到了每次滑动的第一个问题,不是在不同的单元格上停止,而是在页面上停止。

然后我尝试在 ScrollViewWillEndDecelerating 中输入代码并手动处理分页。但是我的问题是更改集合视图 ContentOffset 或滚动到 Point 都不起作用,除非在 LayoutSubiews 中调用。这是它们影响 CollectionView 的唯一地方

我的集合视图中的每个单元格都是全屏的。我处理布局子视图中的单元格大小。

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let layout = customCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        let itemWidth = view.frame.width
        let itemHeight = view.frame.height
        layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
        layout.invalidateLayout()
    }


    let ip = IndexPath(row: 2, section: 0)

    view.layoutIfNeeded()
    customCollectionView.scrollToItem(at: ip, at: UICollectionViewScrollPosition.centeredVertically, animated: true)

    let point = CGPoint(x: 50, y: 600)
    customCollectionView.setContentOffset(point, animated: true)

}


func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    let pageHeight = customCollectionView.bounds.size.height
    let videoLength = CGFloat(videoArray.count)

    let minSpace:CGFloat = 10

    var cellToSwipe = (scrollView.contentOffset.y) / (pageHeight + minSpace) + 0.5
    if cellToSwipe < 0 {
        cellToSwipe = 0
    }
    else if (cellToSwipe >= videoLength){
        cellToSwipe = videoLength - 1
    }
    let p = Int(cellToSwipe)
    let roundedIP = round(Double(Int(cellToSwipe)))
    let ip = IndexPath(row: Int(roundedIP), section: 0)

   let ip = IndexPath(row: 2, section: 0)
    view.layoutIfNeeded()
    customCollectionView.scrollToItem(at: ip, at: UICollectionViewScrollPosition.centeredVertically, animated: true)


}
Run Code Online (Sandbox Code Playgroud)

Eli*_*tle 5

首先,我建议使您的视图控制器类符合UICollectionViewDelegateFlowLayout并使用以下委托方法来调整您的视图控制器类的大小UICollectionViewCells

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let size = CGSize(width: view.frame.width, height: view.frame.height)
    return size
}
Run Code Online (Sandbox Code Playgroud)

然后在你的viewDidLoad通话中

customCollectionView.isPagingEnabled = true
Run Code Online (Sandbox Code Playgroud)