Consider a UICollectionView
with flow layout and horizontal direction. By default, cells are ordered from top to bottom, left to right. Like this:
Wouldn't it be a simple solution to have 2 collection views with standart UICollectionViewFlowLayout
?
Or even better: to have a page view controller with horizontal scrolling, and each page would be a collection view with normal flow layout.
The idea is following: in your UICollectionViewController -init method
you create a second collection view with frame offset to the right by your original collection view width. Then you add it as subview to original collection view. To switch between collection views, just add a swipe recognizer. To calculate offset values you can store the original frame of collection view in ivar cVFrame
. To identify your collection views you can use tags.
Example of init
method:
CGRect cVFrame = self.collectionView.frame;
UICollectionView *secondView = [[UICollectionView alloc]
initWithFrame:CGRectMake(cVFrame.origin.x + cVFrame.size.width, 0,
cVFrame.size.width, cVFrame.size.height)
collectionViewLayout:[UICollectionViewFlowLayout new]];
[secondView setBackgroundColor:[UIColor greenColor]];
[secondView setTag:1];
[secondView setDelegate:self];
[secondView setDataSource:self];
[self.collectionView addSubview:secondView];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(swipedRight)];
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(swipedLeft)];
[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[self.collectionView addGestureRecognizer:swipeRight];
[self.collectionView addGestureRecognizer:swipeLeft];
Example of swipeRight
and swipeLeft
methods:
-(void)swipedRight {
// Switch to left collection view
[self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
}
-(void)swipedLeft {
// Switch to right collection view
[self.collectionView setContentOffset:CGPointMake(cVFrame.size.width, 0)
animated:YES];
}
And then it's not a big problem to implement DataSource methods (in your case you want to have 9 items on each page):
-(NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section {
if (collectionView.tag == 1) {
// Second collection view
return self.dataArray.count % 9;
} else {
// Original collection view
return 9; // Or whatever
}
In method -collectionView:cellForRowAtIndexPath
you will need to get data from your model with offset, if it's second collection view.
Also don't forget to register class for reusable cell for your second collection view as well. You can also create only one gesture recognizer and recognize swipes to the left and to the right. It's up to you.
I think, now it should work, try it out :-)