如何在UICollectionView中更改滚动方向?

时间:2013-08-27 11:29:34

标签: ios objective-c scroll uicollectionview orientation

我在基于 iOS 应用的故事板中有 UICollectionView 。 当设备处于纵向方向时,我希望它能够垂直滚动,而当它在Landscaper中时,我希望它能够水平滚动。

在UICollectionView中,我可以看到 scrollEnabled 成员,但我看不到设置滚动方向的方法。我错过了什么吗?

6 个答案:

答案 0 :(得分:59)

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);
    }

答案 1 :(得分:13)

设置集合视图的scrollDirection collectionViewLayout

文档为here

答案 2 :(得分: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
    }

}

答案 3 :(得分:7)

Swift 4和4.2

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

答案 4 :(得分:3)

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

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

答案 5 :(得分:1)

在故事板中执行此操作。从身份检查员和选择方向,并给你的方向。 enter image description here