Reputation: 7360
I am using collection view for the first time and I'm not sure how to do something..
I have a UICollectionView with 12 cells. I set the collectView to scroll horizontally only and cells are lined up next to each other. I also turned on paging so I could use UIPageControll to indicate scrolling is active.
I want the collection view to only show four cells on the screen at any time. When the view loads, I get four cells, no problem. However when I scroll horizontally, I get 4 and a half cells. never just four.
Is there a way to tell the collection view only to show four cells at a time?
Upvotes: 1
Views: 534
Reputation: 1421
you can statically add number of cell(items)in collection view,if not require dynamic.
here I am using Scroll Direction Horizontal you can do it same way in vertical. hope this will help
you can do this way also. Just copy this code into your view controller and make some changes.
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
NSIndexPath *indexPath;
for (UICollectionViewCell *cell in [self.collectionView visibleCells]) {
indexPath = [self.collectionView indexPathForCell:cell];
NSLog(@"%@",indexPath);
}
UICollectionViewCell *cell =(UICollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
//finally get the rect for the cell
CGRect cellRect = cell.frame;
self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, cellRect.origin.y);
}
Upvotes: 2
Reputation: 42588
As Marc said, you could simply control the size of your collection view.
If changing the size is not practical, then you can set content inset on the collection view.
CGFloat cellWidth = … // Cell width
CGFloat collectionViewWidth = … // Collection View Width
CGFloat desiredCollectionViewWidth = cellWidth * 4.0;
CGFloat horizontalInset = collectionViewWidth - desiredCollectionViewWidth;
// To center the collection view
UIEdgeInsets inset = UIEdgeInsetsMake(0, horizontalInset/2, 0, horizontalInset/2);
self.collectionView.contentInset = inset;
// Or, to left justify the collection view
UIEdgeInsets inset = UIEdgeInsetsMake(0, 0, 0, horizontalInset);
self.collectionView.contentInset = inset;
Upvotes: 1