如何在 Swift 的 UIViewController 中添加多个集合视图?

How can I add multiple collection views in a UIViewController in Swift?

我试了很多天才意识到这一点:

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

如果有人能帮助我,我会很高兴。 :)

是的--这是完全可能的。您可以将它们各自的 UICollectionViewDelegates/UICollectionViewDataSources 分配给不同的 类 或将 CollectionView 子类化,将委托和数据源分配给当前的 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)    
    }
}

像这样子类化 UICollectionView:

class CustomCollectionViewA: UICollectionView {
    // add more subclass code as needed
}

class CustomCollectionViewB: UICollectionView {
    // add more subclass code as needed
}

这是可能的,您只需将每个 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
}

您还可以以不同方式命名集合视图出口(无需子类化):

@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;
}

这是另一种方式。

您可以使用工厂设计模式构建两个不同的集合视图,并 return 通过函数构建它们。这是 swift 4.

的工作版本

这段代码放在一个单独的帮助文件中:

import UIKit

class collectionViews {

static func collectionViewOne() -> UICollectionView {

    let layout = UICollectionViewFlowLayout()
    let collectionViewOne = UICollectionView(frame: CGRect(x: 0, y: 20, width: 200, height: 100), collectionViewLayout: layout)
    return collectionViewOne

}

static func collectionViewTwo() -> UICollectionView {

    let layout = UICollectionViewFlowLayout()
    let collectionViewTwo = UICollectionView(frame: CGRect(x: 0, y: 300, width: 200, height: 100), collectionViewLayout: layout)
    return collectionViewTwo

}


}

这里是视图控制器代码:

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {


let collectionViewOne = collectionViews.collectionViewOne()
let collectionViewTwo = collectionViews.collectionViewTwo()

var myArray = ["1", "2"]
var myArray2 = ["3", "4"]

override func viewDidLoad() {
    super.viewDidLoad()


    collectionViewOne.delegate = self
    collectionViewOne.dataSource = self
    collectionViewOne.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
    view.addSubview(collectionViewOne)


    collectionViewTwo.delegate = self
    collectionViewTwo.dataSource = self
    collectionViewTwo.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell2")
    view.addSubview(collectionViewTwo)

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if collectionView == self.collectionViewOne {
        return myArray.count
    } else {
        return myArray2.count
    }

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == self.collectionViewOne {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath)

        myCell.backgroundColor = UIColor.red

        return myCell

    } else {

        let myCell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell2", for: indexPath as IndexPath)

        myCell2.backgroundColor = UIColor.blue

        return myCell2
    }

}


}

Result

这是 swift 5 和 Xcode 11 的工作版本:

为相应的集合视图创建出口:出口:

@IBOutlet weak var bgCollectionView: UICollectionView!
@IBOutlet weak var frontCollectionView: UICollectionView!
var arrImages = [String : [UIImage]]()

arrImages 包含 like

override func viewDidLoad() {
        super.viewDidLoad()
    arrImages = [
    "frontImg": [//Front UIImage array],
    "bgImg": [//Background UIImage array]
    ]
}

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let arrImg = arrImages["bgImg"] {
            return arrImg.count
        } else if let arrImg = arrImages["frontImg"]{
            return arrImg.count
        }
        return 0
    }

您可以通过两种方式完成此操作

  1. 使用 CollectionView 插座

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell    
    if collectionView == self.bgCollectionView{
            if let arrImg = arrImages["bgImg"]{
                cell.imgView.image = arrImg[indexPath.row]
            }
        }else{
            if let arrImg = arrImages["frontImg"]{
                cell.imgView.image = arrImg[indexPath.row]
            }
        }
        return cell
    }
  1. 使用 CollectionView 标签: 这里Background Images collectionview tag为1,Front Images collectionview tag为2.

    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
        if collectionView == collectionView.viewWithTag(1){
            if let arrImg = arrImages["bgImg"]{
                cell.imgView.image = arrImg[indexPath.row]
            }
        }else{
            if let arrImg = arrImages["frontImg"]{
                cell.imgView.image = arrImg[indexPath.row]
                }
            }
            return cell
        }
     
    

请像这样在 CollectionView 中添加标签:

谢谢。希望它对你有用!!