Swift CollectionView垂直分页

时间:2016-11-20 08:19:17

标签: swift scrollview paging collectionview

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

然后我尝试在ScrollViewWillEndDecelerating中手动输入代码并处理分页。 但是我的问题是更改collectviews 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)


}

1 个答案:

答案 0 :(得分:2)

首先,我建议您使视图控制器类符合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
}

然后在viewDidLoad电话

customCollectionView.isPagingEnabled = true
相关问题