Paging UICollectionView by cells, not screen

前端 未结 22 2149
予麋鹿
予麋鹿 2020-12-04 05:00

I have UICollectionView with horizontal scrolling and there are always 2 cells side-by-side per the entire screen. I need the scrolling to stop at the begining

22条回答
  •  没有蜡笔的小新
    2020-12-04 05:35

    This is a straight way to do this.

    The case is simple, but finally quite common ( typical thumbnails scroller with fixed cell size and fixed gap between cells )

    var itemCellSize: CGSize = 
    var itemCellsGap: CGFloat = 
    
    override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
        let pageWidth = (itemCellSize.width + itemCellsGap)
        let itemIndex = (targetContentOffset.pointee.x) / pageWidth
        targetContentOffset.pointee.x = round(itemIndex) * pageWidth - (itemCellsGap / 2)
    }
    
    // CollectionViewFlowLayoutDelegate
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return itemCellSize
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return itemCellsGap
    }
    

    Note that there is no reason to call a scrollToOffset or dive into layouts. The native scrolling behaviour already does everything.

    Cheers All :)

提交回复
热议问题