在UIViewController中的多个collectionView – IOS的​​快速

我试了很多天才意识到这一点: 在这里输入图像说明

我想在我的UIViewController中添加两个不同的CollectionView。 例如,我想要在这些collectionView中的图像每个CollectionView使用自己的图像。 这可能吗?

如果有人能帮我一把,我会很开心的。 🙂

这是可能的,您只需要将每个UICollectionView添加为子视图,并将委托和数据源设置为您的UIViewController。

这是一个简单的例子。 假设你有一个UICollectionView的工作,你应该能够适应这个代码到你自己的使用很容易添加一个:

let collectionViewA = UICollectionView() let collectionViewB = UICollectionView() let collectionViewAIdentifier = "CollectionViewACell" let collectionViewBIdentifier = "CollectionViewBCell" override func viewDidLoad() { // Initialize the collection views, set the desired frames collectionViewA.delegate = self collectionViewB.delegate = self collectionViewA.dataSource = self collectionViewB.dataSource = self self.view.addSubview(collectionViewA) self.view.addSubview(collectionViewB) } 

在cellForItemAtIndexPath委托函数中:

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if collectionView == self.collectionViewA { let cellA = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewAIdentifier) as UICollectionViewCell // Set up cell return cellA } else { let cellB = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewBIdentifier) as UICollectionViewCell // ...Set up cell return cellB } } 

在numberOfItemsInSection函数中:

 func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == self.collectionViewA { return 0 // Replace with count of your data for collectionViewA } return 0 // Replace with count of your data for collectionViewB } 

是的 – 这是完全可能的。 您可以将其各自的UICollectionViewDelegates / UICollectionViewDataSources分配给不同的类或子类CollectionViews,将委托和数据源分配给您当前的viewController,并在委托方法中向下引用collectionView,如下所示:

 @IBOutlet collectionViewA: CustomCollectionViewA! @IBOutlet collectionViewB: CustomCollectionViewB! func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if let a = collectionView as? CustomCollectionViewA { return a.dequeueReusableCellWithIdentifier("reuseIdentifierA", forIndexPath: indexPath) } else { return collectionView.dequeueReusableCellWithIdentifier("reuseIdentifierB", forIndexPath: indexPath) } } 

为相应的collections视图创build网点:网点:

 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var SecondCollectioView: UICollectionView! 

方法:

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as UICollectionViewCell if(collectionView == self.SecondCollectioView) { cell.backgroundColor = UIColor.black } else { cell.backgroundColor = self.randomColor() } return cell; } 

这将是另一种方式。