2016-11-20 57 views
0

我在我的collectionview上启用了分页,并遇到了不是在不同的单元格上停止的每个刷卡的第一个问题,而是页面。Swift CollectionView垂直分页

然后我尝试输入代码并在ScrollViewWillEndDecelerating中手动处理分页。 然而,我的问题是改变collectionviews的ContentOffset或滚动到一个点都不工作,除非在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) 


} 

回答

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