The end result is to have 2 collection views on one view controller. Both pulling from different sources as well as one should scroll horizontally while the other vertically.
Please advise on how to achieve this programatically.
This is possible, you just need to add each UICollectionView as a subview, and set the delegate and dataSource to your UIViewController.
Alternatively, you can drag more than one cell from the Object Library into your collection view, assign a subclass and reuse identifier for the cell and design it as needed. Just like you would for a single cell.
An object that manages an ordered collection of data items and presents them using customizable layouts.
I haven't used UICollectionView
before, but as it inherits from UIScrollView, I'm taking a chance that it's pretty similar to UITableView
.
When using one CollectionView, I'm assuming you have to set collectionView.delegate = self;
and collectionView.dataSource = self
, and in the .h
-file, make sure your class is using <UICollectionViewDelegate, UICollectionViewDataSource>
or something similar. When you're setting the delegate of the collectionView to your own view (self
), you're making sure that the data provided for the collectionView comes from your own class, in the delegate-methods. I'm sure you already know this, as that should be pretty straight forward with one single collectionView.
When you are using two collectionViews, then you have to set
collection1.delegate = self;
collection2.delegate = self;
collection1.dataSource = self;
collection2.dataSource = self;
This will in turn do so that both collectionViews will call the delegate methods.
For instance, the delegate method -collectionView:cellForItemAtIndexPath:
will be called twice. Once for collection1, and once for collection2.
To make sure they get the correct data sent to them, you should create a simple check in the beginning of every delegate and dataSource method, like this:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
if(collectionView == collection1)
{
//return cell for collection1
}
else
{
//return cell for collection2
}
}
Here, I'm checking if collectionView
is equal to collection1
or collection2
. The delegate methods are providing collectionView
as the UICollectionView it is calling the method for, and that has to be either of the two. This can look suspicious if you have called one of your collectionViews for collectionView
though, so be sure to name them logically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With