本文介绍了如何在Swift的UIViewController中添加多个集合视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了很多天才意识到这一点:$ b​​ $ b

I tried many days to realise this:

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

I want to add in my UIViewController two different CollectionView.For example I want to put images in these collectionViewEach CollectionView use its own images.Is this possible?

如果有人可以帮我,我会很高兴。 :)

I will be very happy if somebody can give me a hand. :)

推荐答案

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

This is possible, you just need to add each UICollectionView as a subview, and set the delegate and dataSource to your UIViewController.

这是一个简单的示例。假设您有一个UICollectionView,您应该能够使此代码适应您自己的用途,从而轻松添加第二个代码:

Here's a quick example. Assuming you have one UICollectionView working, you should be able to adapt this code to your own uses to add a second fairly easily:

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委托函数中:

In the cellForItemAtIndexPath delegate function:

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函数中:

In the numberOfItemsInSection function:

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
}

这篇关于如何在Swift的UIViewController中添加多个集合视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 04:15