How to get the number of items from a collection data source

I am new to Collectionviewbut not iOS. I use custom Flowlayout for my view. I need to return the content based on the current number of items returned by the CollectionView data source. Does anyone even know how many items are currently in the flowlayout collection?

@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;
}
+4
source share
4 answers

UICollectionViewFlowLayout is a subclass of UICollectionViewLayout. Therefore, it must have access to the UICollectionView, which must know how many elements there are.

[self.collectionView numberOfItemsInSection:0];

, , .

:

[self.collectionView numberOfSections];

, !:)

+16

/outlet collectionView, :

for (int i = 0; i<[collectionView numberOfSections];i++) {//Iterate through all the sections in collectionView
    for (int j = 0; j<[collectionView numberOfItemsInSection:i]; j++) {//Iterate through all the rows in each section
        numOfItems++;
    }
}
+1

Swift ( , ):

let totalItemCount = sections.reduce(0) { result, section -> Int in
   return result + section.items.count
}

section items .

+1
+ (NSInteger)countInCollectionView:(UICollectionView *)collectionView {
   NSInteger itemCount = 0;
   for( int section = 0; section < [collectionView numberOfSections]; ++section ){
      itemCount += [collectionView numberOfItemsInSection:section];
   }
   return itemCount;
}
0

Source: https://habr.com/ru/post/1523510/


All Articles