46

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?

4

6 回答 6

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

prepareForLayout还要注意,在您的流程布局中调用它似乎很好......

@interface LayoutHorizontalThings : UICollectionViewFlowLayout
@end

@implementation LayoutHorizontalBooks
-(void)prepareLayout
    {
    [super prepareLayout];

    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    self.minimumInteritemSpacing = 0;
    self.minimumLineSpacing = 0;
    self.itemSize = CGSizeMake(110,130);
    self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
于 2013-12-06T10:59:37.330 回答
12

设置scrollDirection集合视图的collectionViewLayout.

文档在这里

于 2013-08-27T11:37:23.107 回答
12

斯威夫特 4 和 4.2

if let layout = collectionViewObj.collectionViewLayout as? UICollectionViewFlowLayout {
        layout.scrollDirection = .vertical  // .horizontal
    }
于 2017-12-11T18:03:19.940 回答
9

你应该试试这个:

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

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

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

在斯威夫特:

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
    }
    else{
       layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
    }

}
于 2015-07-14T20:48:52.370 回答
6

感谢 Mundi 和 Dan Rosenstark 的回答,这里是 swift 4.2 版本。

if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
    flowLayout.scrollDirection = .horizontal
}
于 2017-09-14T20:08:35.030 回答
4

在您的Storyboard中执行此操作。从身份检查器中选择滚动方向并选择您的方向。

在此处输入图像描述

于 2017-09-15T04:47:16.340 回答