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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28750108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:01:10  来源:igfitidea点击:

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

iosswiftcollectionview

提问by Masterfego

I tried many days to realise this: enter image description here

我尝试了很多天来意识到这一点: 在此处输入图片说明

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

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

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

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

回答by Sam

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

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

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:

这是一个快速示例。假设您有一个 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)
}

In the cellForItemAtIndexPath delegate function:

在 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
    }
}

In the numberOfItemsInSection function:

在 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
}

回答by kellanburket

Yes--this is entirely possible. You can either assign their respective UICollectionViewDelegates/UICollectionViewDataSources to different classes or subclass the CollectionViews, assigning both the delegate and data source to your current viewController and downcast your reference to collectionView in the delegation methods like so:

是的——这完全有可能。您可以将它们各自的 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)    
    }
}

Subclass UICollectionView like this:

子类 UICollectionView 像这样:

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

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

回答by GvSharma

You can also name the collection views outlets differently (without subclassing):

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

@IBOutlet weak var collectionView: UICollectionView!

@IBOutlet weak var SecondCollectioView: UICollectionView!

method:

方法:

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

This is will be an another way.

这将是另一种方式。

回答by brontea

You can use the factory design pattern to build two different collection views and return them via functions. Here's my working version for swift 4.

您可以使用工厂设计模式来构建两个不同的集合视图并通过函数返回它们。这是我的 swift 4 工作版本。

This code goes in a separate helper file:

此代码位于单独的帮助文件中:

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

}


}

And here is the view controller code:

这是视图控制器代码:

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

结果

回答by Yogesh Patel

Here's my working version for swift 5 and Xcode 11:

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

create outlets for corresponding collectionviews: outlets:

为相应的集合视图创建插座:插座:

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

arrImages is contain like

arrImages 包含像

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
    }

You can do this two ways

你可以通过两种方式做到这一点

  1. Using CollectionView Outlets
  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. Using CollectionView Tag: Here Background Images collectionview tag is 1 and Front Images collectionview tag is 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
        }
     
  1. 使用 CollectionView 标签:这里背景图片 collectionview 标签是 1,Front Images collectionview 标签是 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
        }
     

Please Add Tag in CollectionView Like this: enter image description here

请在 CollectionView 中添加标签,如下所示: 在此处输入图片说明

Thank You. Hope It's working for you !!

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