我基于故事板的 iOS 应用程序中有一个 UICollectionView。 当设备处于纵向时,我希望它垂直滚动,当它处于 Landscaper 中时,我希望它水平滚动。
在 UICollectionView 中,我可以看到 scrollEnabled 成员,但我看不到如何设置滚动方向。我是不是错过了什么?
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);
}
Swift 4 和 4.2
if let layout = collectionViewObj.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .vertical // .horizontal
}
你应该尝试这个:
- (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
}
}
感谢 Mundi 和 Dan Rosenstark 的回答,这是 swift 4.2 版本。
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.scrollDirection = .horizontal
}
设置布局方向
if let flowLayout = yourCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.scrollDirection = .horizontal
yourCollectionView.collectionViewLayout = flowLayout
}