如何在Swift中实现多个Collection视图

在我的Swift旅程中,我一直在寻找一种简单的方法来将2个或更多集合视图实现到一个UIView中。 为了在numberOfItemsInSection和cellForItemAt方法中引用这两个视图,需要在单独的“帮助”文件中进行设置,如下所示:

 导入UIKitclass collectionViews { 
静态函数collectionViewOne()-> UICollectionView {让布局= UICollectionViewFlowLayout()让collectionViewOne = UICollectionView(frame:CGRect(x:0,y:20,width:200,height:100),collectionViewLayout:layout)return collectionViewOne}
静态函数collectionViewTwo()-> UICollectionView {let layout = UICollectionViewFlowLayout()let collectionViewTwo = UICollectionView(frame:CGRect(x:0,y:300,width:200,height:100),collectionViewLayout:layout)返回collectionViewTwo}
}类标签{静态函数labelArray()-> [UILabel] {让labelA = UILabel(frame:CGRect(x:0,y:0,width:100,height:50))labelA.text =“我是“ let labelB = UILabel(frame:CGRect(x:0,y:0,width:100,height:50))labelB.text =” i'm b“ let myArray = [labelA,labelB]返回myArray}}

这是主View Controller文件的代码:

 导入UIKit类ViewController:UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {让collectionViewOne = collectionViews.collectionViewOne()让collectionViewTwo = collectionViews.collectionViewTwo()var myArray:[UILabel] = labels.labelsArray()var myArray2:[UILabel] = labels.labelsArray()覆盖func viewDidLoad(){super.viewDidLoad() 
collectionViewOne.delegate =自己collectionViewOne.dataSource =自己collectionViewOne.register(UICollectionViewCell.self,forCellWithReuseIdentifier:“ MyCell”)view.addSubview(collectionViewOne)collectionViewTwo.delegate =自己collectionViewTwo.dataSource =自己collectionViewTwo.register(UICollectionViewCell.self,forCellWithReuseIdentifier: “ MyCell2”)view.addSubview(collectionViewTwo)} func collectionView(_ collectionView:UICollectionView,numberOfItemsInSection部分:Int)-> Int {如果collectionView == self.collectionViewOne {return myArray.count} else {return myArray2.count}}
func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath)-> UICollectionViewCell {如果collectionView == self.collectionViewOne {让myCell = collectionView.dequeueReusableCell(withReuseIdentifier:“ MyCell”,用于:indexPath作为IndexPath)myCell.backgroundColor = UIColor。红色myCell.addSubview(myArray [indexPath.row])返回myCell}否则{让myCell2 = collectionView.dequeueReusableCell(withReuseIdentifier:“ MyCell2”,用于:indexPath作为IndexPath)myCell2.backgroundColor = UIColor.blue myCell2.addSubview(myArray2 [indexPath .row])返回myCell2}}}

如您所见,这些方法使用if / else语句构造每个视图。 结果如下:

谢谢阅读!