Вопрос

I have a UICollectionView in a container View. It is sized in such a way that I see only one cell at a time. I have disabled vertical scrolling so only horizontal scrolling takes place.

Everything works just peachy where I scroll horizontally across cells. The disadvantage of this scrolling is I can scroll and get to a position where I see half portion of two cells with a gap in between.

What I want to achieve is to show only one cell at a time and never show two half cells. So the scrolling should take me to the next cell one at a time.

Hope this makes sense.

Please let me know if anyone has tried or can help me to achieve the same. Thanks.

Это было полезно?

Решение

You can scroll one cell at a time by setting pagingEnabled = YES. Or for regular scrolling, you can adjust where the deceleration ends by overriding targetContentOffsetForProposedContentOffset:withScrollingVelocity: of UICollectionViewLayout. When using the later method, you would typically do the following:

  1. Determine the nearest index path to proposedContentOffset. If there are no gaps between your cells, you can use [UICollectionView indexPathForItemAtPoint:]. Otherwise, you may have to inspect your layout in some way to determine which index path you want to scroll to.
  2. Determine the frame of the index path you want to scroll to by getting the layout attributes for that index path
  3. Determine the content offset that will position the given frame where you want it.

Другие советы

Make sure your padding between cells is set to zero as well. Paging enabled will stop on multiples of the view bounds.

    // Set up flow layout
            var flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout();
            flowLayout.minimumInteritemSpacing = 0
            flowLayout.minimumLineSpacing = 0

            collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: flowLayout)

            collectionView!.pagingEnabled = true

Check out my answer over here: ScrollView or CollectionView?

It sounds like you have paging enable but the page size doesn't match you cell size plus the insets left and right of the cell.

Swift 5:

collectionView.isPagingEnabled = true
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top