Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of rows in a section in ios

I am working on collection view and I want number of rows in previous section. Is there any method which return number of row in section. Please help me.

like image 514
Niks Avatar asked Aug 02 '14 11:08

Niks


2 Answers

The delegate method of the UICollectionView dataSource that you will need to implement in order to display the cells can be invoked manually.

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

Therefore you can call it using:

NSInteger numberOfRows = [self collectionView:self.collectionView numberOfItemsInSection:MAX(0, currentSection - 1)];

You do not want to get an out of bounds exception so I have capped it at 0*

EDIT

@holex raises a very good point - I was assuming you only had one column.

If you know the size of your items width you can do the following:

//Assuming a fixed width cell

NSInteger section = 0;
NSInteger totalItemsInSection = [self.feedCollectionView numberOfItemsInSection:section];

UIEdgeInsets collectionViewInset = self.feedCollectionView.collectionViewLayout.sectionInset;
CGFloat collectionViewWidth = CGRectGetWidth(self.feedCollectionView.frame) - collectionViewInset.left - collectionViewInset.right;
CGFloat cellWidth = [self.feedCollectionView.collectionViewLayout itemSize].width;
CGFloat cellSpacing = [self.feedCollectionView.collectionViewLayout minimumInteritemSpacing];

NSInteger totalItemsInRow = floor((CGFloat)collectionViewWidth / (cellWidth + cellSpacing));
NSInteger numberOfRows = ceil((CGFloat)totalItemsInSection / totalItemsInRow);

NSLog(@"%@", @(numberOfRows));

We determine how many items will appear in a row, to be a able to determine the amount of rows in the section.

like image 60
William George Avatar answered Sep 29 '22 02:09

William George


There are two method in collectionview, notice that the method are not in the delegate of collectionview.

- (NSInteger)numberOfSections;
- (NSInteger)numberOfItemsInSection:(NSInteger)section;

You can call [self.collectionView numberOfSections]; to find the sectionCount.

You can call [self.collectionView numberOfItemsInSection:somesection]; to find the rows in some section.

like image 30
Suen Avatar answered Sep 29 '22 01:09

Suen