Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paging in Collection View not centering properly

I have a UICollectionView with paging enabled and the individual views that are moving horizontally are not getting centered properly. I have made sure that the views are the same width as the screen.

Any pointers on how to force the UICollectionView to page the views horizontally?

like image 354
Nirma Avatar asked Mar 04 '13 15:03

Nirma


1 Answers

You have to make sure that your section inset + line spacing + cell width all equals exactly the bounds of the CollectionView. I use the following method on a custom UICollectionViewFlowLayout sublcass:

- (void)adjustSpacingForBounds:(CGRect)newBounds {
  NSInteger count = newBounds.size.width / self.itemSize.width - 1;

  CGFloat spacing = (newBounds.size.width - (self.itemSize.width * count)) / count;

  self.minimumLineSpacing = spacing;

  UIEdgeInsets insets = self.sectionInset;
  insets.left = spacing/2.0f;
  self.sectionInset = insets;
}

You have to remember that UICollectionView is just a sublcass of UIScrollView so it doesn't know how you want your pagination to work. Before UICollectionView you would have to handle all of this math when laying out your subviews of the UIScrollView.

like image 108
CEarwood Avatar answered Oct 18 '22 17:10

CEarwood