UICollectionView numberOfItemsInSection being called twice
<p>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. </p>

<p>The viewDidLoad looks like this-</p>

<pre><code>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 

}
</code></pre>

<p>Each collectionView is associated with a tag in the viewDidLoad.</p>

<pre><code>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) -&gt; Int {
    return noOfItemsArray[collectionView.tag]
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -&gt; UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
    cell.backgroundColor = UIColor.redColor()
    return cell
}
</code></pre>

<p>The app crashes. So for debugging, I modified my numberOfItemsInSection to - </p>

<pre><code>func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {
    print(collectionView.tag)
    return 10
}
</code></pre>

<p>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..)</p>

<pre><code> 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
</code></pre>

<p>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.</p>

<p>Why is this happening and what is the best possible solution to it?</p>

<p>Thank you for your time.</p>