Paging UICollectionView by cells, not screen

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

    Ok so the proposed answers did'nt worked for me because I wanted to scroll by sections instead, and thus, have variable width page sizes

    I did this (vertical only):

       var pagesSizes = [CGSize]()
       func scrollViewDidScroll(_ scrollView: UIScrollView) {
            defer {
                lastOffsetY = scrollView.contentOffset.y
            }
            if collectionView.isDecelerating {
                var currentPage = 0
                var currentPageBottom = CGFloat(0)
                for pagesSize in pagesSizes {
                    currentPageBottom += pagesSize.height
                    if currentPageBottom > collectionView!.contentOffset.y {
                        break
                    }
                    currentPage += 1
                }
                if collectionView.contentOffset.y > currentPageBottom - pagesSizes[currentPage].height, collectionView.contentOffset.y + collectionView.frame.height < currentPageBottom {
                    return // 100% of view within bounds
                }
                if lastOffsetY < collectionView.contentOffset.y {
                    if currentPage + 1 != pagesSizes.count {
                        collectionView.setContentOffset(CGPoint(x: 0, y: currentPageBottom), animated: true)
                    }
                } else {
                    collectionView.setContentOffset(CGPoint(x: 0, y: currentPageBottom - pagesSizes[currentPage].height), animated: true)
                }
            }
        }
    

    In this case, I calculate each page size beforehand using the section height + header + footer, and store it in the array. That's the pagesSizes member

提交回复
热议问题