简体   繁体   中英

Scrolling to next cell in UICollectionView

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.

斯威夫特 5:

collectionView.isPagingEnabled = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM