2016-11-20 97 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