UICollectionView numberOfItemsInSection被调用两次

Abh*_*729 1 objective-c ios uicollectionview swift

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

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 

}
Run Code Online (Sandbox Code Playgroud)

每个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
}
Run Code Online (Sandbox Code Playgroud)

该应用程序崩溃。因此,为了进行调试,我将我的numberOfItemsInSection修改为-

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    print(collectionView.tag)
    return 10
}
Run Code Online (Sandbox Code Playgroud)

我发现numberOfItemsInSection首先被带有标签5的collectionView调用。它被为此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
Run Code Online (Sandbox Code Playgroud)

现在,由于numberOfItemsInSection始终返回10,因此我可以在每个Collectionview中看到10个项目。但是在更早的时候,当我返回noOfItemsArray [collectionView.tag]时,由于这两个调用返回了不同的值,所以我的应用程序崩溃了。

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

感谢您的时间。

小智 6

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