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

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

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

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

还要注意,在stream布局的prepareForLayout中调用这个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); } 

设置集合视图的collectionViewLayoutscrollDirection

文档在这里 。

你应该试试这个:

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

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

荣誉蒙迪和丹·罗森斯塔克为他们的答案,这里是迅速的3版本。

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

在你的故事板中做到这一点。 从身份检查员,select方向,并给你的方向。 在这里输入图像说明

斯威夫特4

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