Search code examples
iosdatasourceuicollectionviewuicollectionviewlayout

How to get number of items from collectionview's data source


I am new to Collectionview, but not to iOS. I am using custom Flowlayout for my collectionview. I need to return contentsize based on current number of items returned by CollectionView's data source. Is there anyway to know how many items are there currently in flowlayout's collectionview?

@interface LatestNewsFlowLayout : UICollectionViewFlowLayout

-(id)initWithSize:(CGSize) size;

@end

@implementation LatestNewsFlowLayout

-(id)initWithSize:(CGSize) size {
    self = [super init];
    if (self) {
        self.itemSize = size;
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.sectionInset = UIEdgeInsetsMake(0, 10.0, 0, 0);
        self.minimumLineSpacing = 5;
    }
    return self;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)oldBounds {
    return YES;
}

-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *answer = [[super layoutAttributesForElementsInRect:rect] mutableCopy];

    for(int i = 1; i < [answer count]; ++i) {
        UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
        UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];
        NSInteger maximumSpacing = 5;
        NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
        if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = origin + maximumSpacing;
            currentLayoutAttributes.frame = frame;
        }
    }

    return answer;
}

-(CGSize) collectionViewContentSize
{
    CGSize size;
    int numOfItems = ???
    size.width = 100 * numOfItems;
    size.height = 100;
    return size;
}

Solution

  • The UICollectionViewFlowLayout is a subclass of UICollectionViewLayout. It should therefore have access to the UICollectionView which should know how many items there are.

    [self.collectionView numberOfItemsInSection:0];
    

    You may need to iterate over the section to get the total number of items if you have more that one section.

    You can get the number of sections similarly:

    [self.collectionView numberOfSections];
    

    Hope this helps! :)