Paging UICollectionView by cells, not screen

前端 未结 22 2083
予麋鹿
予麋鹿 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:48

    Here's the easiest way that i found to do that in Swift 4.2 for horinzontal scroll:

    I'm using the first cell on visibleCells and scrolling to then, if the first visible cell are showing less of the half of it's width i'm scrolling to the next one.

    If your collection scroll vertically, simply change x by y and width by height

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
        targetContentOffset.pointee = scrollView.contentOffset
        var indexes = self.collectionView.indexPathsForVisibleItems
        indexes.sort()
        var index = indexes.first!
        let cell = self.collectionView.cellForItem(at: index)!
        let position = self.collectionView.contentOffset.x - cell.frame.origin.x
        if position > cell.frame.size.width/2{
           index.row = index.row+1
        }
        self.collectionView.scrollToItem(at: index, at: .left, animated: true )
    }
    

提交回复
热议问题