如何重用 Collection View? -Swift

How to reuse a Collection View? -Swift

在我尝试构建的应用程序中,我需要很多 UICollectionView(大约 10 个)。我决定在不使用 Storyboards 的情况下制作 collectionViews(即完全在代码中)。 故事板 使事情复杂化(对于许多 collectionView)。

代码如下:

我)

   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)

 // 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)
}
 }

这会在 View Controller 中创建一个 collectionView,但是如果我必须再创建十个这样的,我将不得不重写上面的代码 10 次。

所以我尝试创建一个单独的 MyCollectionView class,其中包含将 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)   

 }

或类似的东西。然而我没有成功。 我该怎么办?谢谢!

虽然我不确定这是否是您想要的,但我只会给您举个简单的例子。同样,这完全取决于您正在实施的设计,但这可能是其中一个想法。

想法是

  1. 创建一个集合视图,它将填充您要添加的 10 个集合视图。

  2. 创建一个包含您要重复的集合视图的集合视图单元格。

  3. 将不同的数据(食物、鞋子、汽车等)提供给集合视图单元格 (MYCollectionView)。

  4. 将每个数据馈送到单元格中的集合视图以填充单个数据。

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

我的ViewController

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")
    }
}

更新: 由于问题只是关于重用集合视图,所以我并没有真正将数据一直传递到重用集合视图。假设当加载视图控制器时你有数据,比如鞋子、食物和汽车的数组,每个数组组件也是数组。

例如,

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

现在您的数据数组有 3 个组件,这将决定您在问题中创建的集合视图的数量。所以在我的示例代码的视图控制器中,

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
}

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

为了使其干净,您的数据对象应该具有公共基础模型,以便您可以将它们从视图控制器一直传递到 MYCollectionView 中的集合视图。