How can I change the scroll direction in UICollectionView?

2020/12/16 01:42 · ios ·  · 0评论

I have a UICollectionView in my storyboard based iOS app.
When the device is in the portrait orientation I'd like it to scroll vertically, and when it's in Landscaper I'd like it to scroll horizontally.

In UICollectionView I can see the scrollEnabled member, but I can see no way to set the scroll direction. Have I missed something?

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];

Note too that it seems to be fine to call this in prepareForLayout in your flow layout...

@interface LayoutHorizontalThings : UICollectionViewFlowLayout

@implementation LayoutHorizontalBooks
    [super prepareLayout];

    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    self.minimumInteritemSpacing = 0;
    self.minimumLineSpacing = 0;
    self.itemSize = CGSizeMake(110,130);
    self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);

Set the scrollDirection of the collection view's collectionViewLayout.

Docs are here.

You should try this:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{

  UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)[self.collectionView collectionViewLayout];

  if ((toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) || (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft)){
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;

In Swift:

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {

    var layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout

    if ((toInterfaceOrientation == UIInterfaceOrientation.LandscapeLeft) || (toInterfaceOrientation == UIInterfaceOrientation.LandscapeRight)){

        layout.scrollDirection = UICollectionViewScrollDirection.Vertical
       layout.scrollDirection = UICollectionViewScrollDirection.Horizontal


Swift 4 and 4.2

if let layout = collectionViewObj.collectionViewLayout as? UICollectionViewFlowLayout {
        layout.scrollDirection = .vertical  // .horizontal

Kudos to Mundi and Dan Rosenstark for their answer, here's the swift 4.2 version.

if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
    flowLayout.scrollDirection = .horizontal

Do that in your Storyboard. From identity inspector and select the
Scroll Direction and choose your direction.

enter image description here

文章标签: ,   ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!