【问题标题】:UICollectionView: How to keep the items of a section in a single row?UICollectionView:如何将部分的项目保持在一行中?
【发布时间】:2015-04-08 03:34:53
【问题描述】:

我想在UICollectionView 中包含三个部分。 每个部分应在同一行中显示其项目。如果项目不适合屏幕,它们仍应保留在同一行中,用户应向右滚动以查看所有项目。

简而言之,我想防止项目flow 进入下一行。希望有道理。

我发现了一些奇怪的解决方案,如here。但是,如果您有多个部分,这些都不起作用。

我该如何解决这个问题? Storyboard 上有设置吗,还是我必须使用自定义布局?

【问题讨论】:

  • 你需要一个自定义布局。

标签: ios uicollectionview


【解决方案1】:

使用多个 UICollectionView,每个都有自己的可滚动区域。

【讨论】:

    【解决方案2】:

    我不久前写了这个布局,但我认为它应该仍然有效。数据源是一个数组数组,所以每一行都是一个新的部分。这是流布局类,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 2016-07-15
      • 1970-01-01
      • 2013-10-01
      相关资源
      最近更新 更多