iosswiftuiscrollviewcgpointscroll-paging

UICollectionView Scroll to next item


The idea is replacing PageController with UIScrollView, UIScrollView should only scroll to the next/previous item and stop. I've found a few solutions, but I've only understood that I've to use targetContentOffsetForProposedContentOffset, but have no idea what CGPoint should I return and how to stop on the next item even if user scrolls with high velocity.

    override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
    return CGPoint(x: 0, y: 0)
   }

Solution

  • With UIScrollView, you can enable paging. The property is called pagingEnabled. This means if it will snap to full widths (or heights) providing you set the content size properly.

    i.e. If you want 2 pages and have a width of 100 and height of 200. You set the content size to be CGSize 200 for width and 200 for height. The scroll view will handle the snapping and paging.

    If you want to have a function to go to a page like goToPage(2). Then you just need to call scrollRectToVisible method in UIScrollView with a CGRect of (pageNumber * scrollView.width (or page width), 1 height)

    It looks like you are using Swift, so your implementation may vary.