UICollectionView scrolling in both directions

last-Programmer picture last-Programmer · Nov 1, 2012 · Viewed 36.2k times · Source

I made a UICollectionView with a vertical scroll.

The width of the cell is more than than the screen width, so I created a customFlowLayout based on UICollectionViewFlow layout returning the right calculated content size.

However, this doesn't work. When the width of the cell is less than the screen width it works. Does it mean that we can't have width more than than screen width in vertical scroll?

It is the same for horizontal scroll, but then the height of the CollectionView is limited to screen height.

Is there any way to make it work?

Answer

johnrechd picture johnrechd · Dec 17, 2013

As others have already said, the UICollectionView can only scroll one direction using a flow layout. However you can accomplish this very easily without creating a custom layout or using a third party library.

When you lay your view out in story board, you can put your UICollectionView embedded in a UIScrollView. Have the scrollview set up to scroll horizontally and the UICollectionView to scroll Vertically. Then set the UICollectionView.delaysContentTouchesto true so touches will pass through to the UIScrollView and not think you are trying to scroll the collectionview.

When you set up the UICollectionView, set it's size and the size of the cells to be what you actually want them to be (Wider than the actual screen) and lay them out accordingly.

Now in the containing UIViewController put this code in the view lifecycle

    - (void)viewDidLayoutSubviews {
        self.myScrollView.contentSize = self.myCollectionView.frame.size;
    }

That's literally all you have to do to accomplish what you are describing. Now your scrollview should allow you to scroll horizontally to view your entire cell and your collectionView should scroll vertically through your cells.

Happy programming.