被调用两次的UICollectionView numberOfItemsInSection

我有我的viewController启用分页scrollView,我想有6个集合视图,这些collectionViews是滚动视图的子视图。 collectionViews中有不同数量的项目。

viewDidLoad看起来像这样 –

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 } 

每个collectionView都与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 } 

该应用程序崩溃。 所以为了debugging,我修改了我的numberOfItemsInSection为 –

 func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { print(collectionView.tag) return 10 } 

我发现numberOfItemsInSection首先被调用的collectionView与标签5.它被调用一次这个collectionView。 但是对于其余的collectionViews,numberOfItemsInSection被调用了两次 – 第一次调用collectionView.tag = 5,然后在第二次调用时,collectionView.tag = 4(3,2,1等等..)

  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 

现在,因为numberOfItemsInSection总是返回10,所以我可以在每个Collectionview中看到10个项目。 但更早的时候,当我返回noOfItemsArray [collectionView.tag],因为2次调用返回不同的值,我的应用程序崩溃。

为什么会发生这种情况,最好的解决办法是什么?

感谢您的时间。

我刚刚遇到同样的问题。 最后,我发现我的问题的原因是我使用相同的布局为collectionViews。 为每个collectionView创build一个布局后,numberOfItemsInSection将只为每个collectionView调用一次。 希望有所帮助。