I have a collectionview that I am using to show thumbnails. I want it to be 4 columns across just like the photos app.
I got some example code (not much out there yet) and it’s confusing me with the math it’s doing.
I’m using an array (thumbs) that I build via NSXMLParser from XML coming back from a web service as the data source.
However, since the array doesn’t have ‘numberOfSections’ nor ‘numberOfItemsInSection'(it’s just a simple 2d array with photonames&locations) I am having trouble determining the math needed to adjust it to handle 4 across.
eg:If it’s the third row/2nd column, is that index 9(zero-base) in the array??
(since 2 full rows * 4 per row + 2(second column) = 10)?.. confused
Also note: the current code will only show an even # of pictures. So if there’s, say 3 pics in a particular album, only 2 will show.
Current Code:
`#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
// Return the number of sections.
return [thumbs count] / 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 2;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCollCell" forIndexPath:indexPath];
//get current photo from collection
PhotoCollection *currentPhoto = [thumbs objectAtIndex:(indexPath.section*2 + indexPath.row)];
//Show in PhotoName Cell
cell.photoName.text = currentPhoto.PhotoName;
//show thumb via:SDWebImage
[cell.photoView setImageWithURL:[NSURL URLWithString:currentPhoto.PhotoThumbnailAbsoluteLocation] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
//regular (wasn't working by default)
//cell.photoView.image = [UIImage imageNamed:currentPhoto.PhotoThumbnailAbsoluteLocation];
return cell;
}`
The point of a collection view is that you don’t need to do these calculations. Use
UICollectionViewFlowLayoutas your layout class, make the cells the appropriate size (so only 4 will fit on a row) and have a single section containing all your thumbnails. The flow layout will give you a grid by automatically adjusting the position of the cells to fill the rows up.