简体   繁体   English

如何重用集合视图? -迅速

[英]How to reuse a Collection View? -Swift

In an application I'm trying to build I need a lot of UICollectionView s (around 10). 在我要构建的应用程序中,我需要很多UICollectionView (大约10个)。 I decided to make the collectionView s without the use of Storyboards (ie entirely in code) . 我决定不使用Storyboard (即完全使用代码)来制作collectionView Storyboards complicate things(for many collectionViews) . 情节提要使事情复杂化(对于许多collectionViews)。

Here is the code: 这是代码:

I) 一世)

   override func viewDidLoad() {

    super.viewDidLoad()
        //Create the collection View      

    let frame =                  CGRect(origin: CGPoint.zero , size: CGSize(width: self.view.frame.width , height: 50))
    let layout =                 UICollectionViewFlowLayout()
     collectionView1 =           UICollectionView(frame: frame, collectionViewLayout: layout)
    collectionView1.dataSource = self
    collectionView1.delegate =   self
    collectionView1.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellIdentifier")
    collectionView1.backgroundColor = UIColor.red
    view.addSubview(collectionView1) }

II) II)

 // TheData Source and Delegate 

extension ViewController : UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{


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

 return 5

}

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


        let cell =              collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath)
        cell.backgroundColor = UIColor.darkGray
        return cell

}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: 50, height: 50)
}
 }

This would create one collectionView in a View Controller , however if I had to create ten more of these I would have to rewrite the above code 10 times . 这将在View Controller中创建一个collectionView ,但是如果我必须再创建其中的10个,则必须重写上述代码10次。

So I tried to create a separate MyCollectionView class with the basic implementation needed to add a collectionView to a ViewController so that all I had to do in my view controller was something as simple as 因此,我尝试创建一个单独的MyCollectionView类,该类具有将collectionView添加到ViewController所需的基本实现,因此我在视图控制器中所做的一切都非常简单

 override func viewDidLoad() {

super.viewDidLoad()

 let shoesCollection = MYCollectionView(frame : ...)
 self.view.addSubview(shoesCollection)   

 let foodCollection = MYCollectionView(frame : ...)
 self.view.addSubview(foodCollection)

 let carCollection = MYCollectionView(frame : ...)
 self.view.addSubview(carCollection)   

 }

or something similar . 或类似的东西。 However I was unsuccessful. 但是我没有成功。 How shall I go about this? 我该怎么办? Thanks! 谢谢!

I will just give you simple example although I'm not sure if this is what you wanted. 我只是给你一个简单的例子,尽管我不确定这是否是你想要的。 Again, it totally depends on the design you are implementing but this could be one of the ideas. 同样,这完全取决于您要实现的设计,但这可能是想法之一。

The idea is 这个想法是

  1. Create a collection view that will populate 10 collection views you want to add. 创建一个集合视图,该视图将填充要添加的10个集合视图。

  2. Create a collection view cell that has the collection view you want to repeat. 创建具有要重复的集合视图的集合视图单元格。

  3. Feed different data(food, shoes, cars and so on) to the collection view cell (MYCollectionView). 将不同的数据(食物,鞋子,汽车等)输入到收集视图单元格(MYCollectionView)。

  4. Feed each data to the collection view in the cell to populate the individual data. 将每个数据馈送到单元格中的收集视图以填充单个数据。

ViewController 视图控制器

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout  {
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 10
        layout.scrollDirection = .vertical

        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(MYCollectionView.self, forCellWithReuseIdentifier: NSStringFromClass(MYCollectionView.self))
        collectionView.backgroundColor = .clear
        return collectionView
    }()


    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(collectionView)
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        collectionView.frame = view.bounds
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(MYCollectionView.self), for: indexPath) as! MYCollectionView
        return cell
    }


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.bounds.width, height: 100)
    }
}

MYViewController MYViewController

class MYCollectionView: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal

        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate =   self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellIdentifier")
        collectionView.backgroundColor = UIColor.red
        return collectionView
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        contentView.addSubview(collectionView)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        collectionView.frame = bounds
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 15
    }

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath)
        cell.backgroundColor = UIColor.darkGray
        return cell

    }


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: bounds.height, height: bounds.height)
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Clicked")
    }
}

Updated: Since the question was only about reusing collection view I didn't really pass the data all the way to the reused collection views. 更新:由于问题仅在于重用集合视图,因此我并没有真正将数据一直传递给重用的集合视图。 Assuming that when the view controller is loaded you have the data, let say array of shoes, food and cars and also each array components are array too. 假设加载了视图控制器后就拥有了数据,可以说鞋子,食物和汽车的阵列以及每个阵列组件也都是阵列。

For example, 例如,

let shoes = [...] //array of shoes
let foods = [...] //array of foods
let cars = [...] //array of cars
let data = [shoes, foods, cars]

Now your data array has 3 components and this will decide number of the collection view you created in your question. 现在,您的数据数组具有3个组件,这将决定您在问题中创建的集合视图的数量。 So in the view controller in my example code, 因此,在示例代码的视图控制器中,

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return data.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(MYCollectionView.self), for: indexPath) as! MYCollectionView
    let components = data[indexPath.item]
    cell.data = components
    return cell
}

In MYCollectionView, you should have a variable, data. 在MYCollectionView中,应该有一个变量data。

var data:[WhateverYourDataModel] = [] {
    didSet {
        collectionView.releadData()
    }
}

public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return data.count
}

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath)
    cell.backgroundColor = UIColor.darkGray

    //let component = data[indexPath.item]
    //You should create a custom collection view cell to display whatever you want to display with the data, component. 

    return cell
}

To make it clean, your data object should have common base model so you can pass them from view controller all the way down to the collection view in the MYCollectionView. 为了使数据干净,您的数据对象应该具有通用的基本模型,因此您可以将它们从视图控制器一直传递到MYCollectionView中的集合视图。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM