numberOfItemsInSection for multiple UICollectionView inside



我在一个UIViewController里面有三个UICollectionView。然后我为每个UICollectionView设置 IBOutlet

@IBOutlet weak var firstCollectionView: UICollectionView!
@IBOutlet weak var secondCollectionView: UICollectionView!
@IBOutlet weak var thirdCollectionView: UICollectionView!

我为他们设置了委托和数据源。但是当我想像下面这样设置numberOfItemsInSection

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == firstCollectionView {
return 1
} else if collectionView == secondCollectionView {
return 2
} else if collectionView == thirdCollectionView {
return 3
}
}

它一直给我这个错误Missing return in a function expected to return 'Int'

您需要返回 0,因为numberOfItemsInSection您必须返回Int. 你以else if结尾,但 numberOfItemsInSection 仍然需要返回Int值。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == firstCollectionView {
return 1
} else if collectionView == secondCollectionView {
return 2
} else if collectionView == thirdCollectionView {
return 3
} else {
return 0
}
}

为了更好的可读性和更少的代码,我建议你使用switch语句:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch collectionView {
case firstCollectionView:
return 1
case secondCollectionView:
return 2
case thirdCollectionView:
return 3
default:
return 0
}
}

就个人而言,我会为每个集合视图创建一个单独的 dataSource 类,并在 viewDidLoad 中分配它们 -

firstCollectionView.dataSource = FirstDataSource()
secondCollectionView.dataSource = SecondDataSource()
thirdCollectionView.dataSource = ThirdDataSource()

要么在创建每个数据源时向其提供所需的数据,要么让数据源也负责获取数据。在这种情况下,将所有内容放入视图控制器会导致疯狂......

简单的例子 -

class MyDataSource: UICollectionViewDataSource {
var data: [MyData] = [] // set this when instantiating, or provide the means of creating the data which you would have put in the viewController
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell: MyCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath) as? MyCollectionViewCell else {
return UICollectionViewCell()
}
// do stuff to cell
}
}

在视野中控制器 -

self.firstCollectionView.dataSource = MyDataSource()
// etc...

非常简单,它所做的只是将代码分成责任区域,使其更容易管理。

最新更新