Guangyu Wang
Guangyu Wang

Reputation: 147

iOS: UICollectionViewCell auto adjust size according to screen size

I am trying to create 10 cells in the collection view(same size as the screen). When I run my app in iphone5s simulator, the view contains exactly 5 cells. But when I switch to iphone6p simulator, the view contains more than 5 cells. How should I adjust the cell size so that the number of cells in screen are consistent across different screen sizes?

Upvotes: 5

Views: 4693

Answers (2)

Asad Farooq
Asad Farooq

Reputation: 205

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{


return CGSizeMake([(NSString*)[[tagArray objectAtIndex:indexPath.row] objectForKey:@"tag"] sizeWithAttributes:NULL].width+10, 40);

}

Upvotes: 0

Britto Thomas
Britto Thomas

Reputation: 2120

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
   int numberOfCellInRow = 3;
   CGFloat cellWidth =  [[UIScreen mainScreen] bounds].size.width/numberOfCellInRow;
   return CGSizeMake(cellWidth, cellWidth);
}

Upvotes: 15

Related Questions