I have a scrollView with paging enabled in my viewController and I want to have 6 collection views and these collectionViews are subviews of the scroll view. The collectionViews have different number of items in them.
The viewDidLoad looks like this-
override func viewDidLoad() {
super.viewDidLoad()
//Set the frame for scroll view
//Programatically created 6 collection views and added them to scrollView
//Set the content size for scroll view
}
Each collectionView is associated with a tag in the viewDidLoad.
collectionView1.tag = 0
collectionView2.tag = 1 and so on..
And the collectionViews were added to the scroll view serially starting from collectionView with tag 0
let noOfItemsArray = [2, 4, 6, 3 ,8, 7]
// 1st collection view has 2 items, 2nd has 4 and so on..
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return noOfItemsArray[collectionView.tag]
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
cell.backgroundColor = UIColor.redColor()
return cell
}
The app crashes. So for debugging, I modified my numberOfItemsInSection to -
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(collectionView.tag)
return 10
}
I found that numberOfItemsInSection was called first for collectionView with tag 5. It was called once for this collectionView. But for the rest of the collectionViews, numberOfItemsInSection was being called twice - in first call collectionView.tag = 5, and then in second call, collectionView.tag = 4 ( 3,2,1 and so on..)
Output was -
5 //For collectionView with tag 5, called only once
5 //For collectionView with tag 4, the first call to numberOfItemsInSection
4 //For collectionView with tag 4, the second call to numberOfItemsInSection, and so on..
5
3
5
2
5
1
5
0
Now since numberOfItemsInSection was always returning 10, I could see 10 items in each of my Collectionview. But earlier, when i was returning noOfItemsArray[collectionView.tag], since the 2 calls were returning different values, my app crashed.
Why is this happening and what is the best possible solution to it?
Thank you for your time.
I just met the same issue with you. At last, I found the cause of my problem is that I used the same layout for the collectionViews. After creating a layout for each collectionView, numberOfItemsInSection will only called once for each collectionView. Hope that helps.