2015-04-07 9 views
1

我想在UICollectionView內有三個部分。 每個部分應顯示在同一行中的項目。如果項目不適合在屏幕上,它們仍應保持在同一行,用戶應向右滾動以查看全部內容。UICollectionView:如何將一個部分的項目保存在一行中?

簡而言之,我想阻止項目flow進入下一行。希望它是有道理的。

我發現了一些奇怪的解決方案,如here。但是,如果您有多個部分,這些功能並不奏效。

我怎樣才能解決這個問題?故事板上是否有設置,或者我是否必須使用自定義佈局?

+1

您需要一個自定義佈局。 – rdelmar

回答

0

使用多個UICollectionViews,每個都有自己的滾動區域。

0

我前一段時間寫了這個佈局,但我認爲它應該仍然工作。數據源是數組的數組,因此每一行都是一個新的部分。這裏是流程佈局類,

#define space 5 
#import "MultpleLineLayout.h" 

@implementation MultpleLineLayout { // a subclass of UICollectionViewFlowLayout 
    NSInteger itemWidth; 
    NSInteger itemHeight; 
} 

-(id)init { 
    if (self = [super init]) { 
     itemWidth = 60; 
     itemHeight = 60; 
    } 
    return self; 
} 

-(CGSize)collectionViewContentSize { 
    NSInteger xSize = [self.collectionView numberOfItemsInSection:0] * (itemWidth + space); // "space" is for spacing between cells. 
    NSInteger ySize = [self.collectionView numberOfSections] * (itemHeight + space); 
    return CGSizeMake(xSize, ySize); 
} 

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)path { 
    UICollectionViewLayoutAttributes* attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:path]; 
    attributes.size = CGSizeMake(itemWidth,itemHeight); 
    long xValue = itemWidth/2 + path.row * (itemWidth + space); 
    long yValue = itemHeight + path.section * (itemHeight + space); 
    attributes.center = CGPointMake(xValue, yValue); 
    return attributes; 
} 


-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect { 
    NSInteger minRow = (rect.origin.x > 0)? rect.origin.x/(itemWidth + space) : 0; // need to check because bounce gives negative values for x. 
    NSInteger maxRow = rect.size.width/(itemWidth + space) + minRow; 
    NSMutableArray* attributes = [NSMutableArray array]; 
    for(NSInteger i=0 ; i < self.collectionView.numberOfSections; i++) { 
     for (NSInteger j=minRow ; j < maxRow; j++) { 
      NSIndexPath* indexPath = [NSIndexPath indexPathForItem:j inSection:i]; 
      [attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]]; 
     } 
    } 
    return attributes; 
} 
相關問題