且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何才能创建一个包含类型的数组?

更新时间:2023-11-23 08:29:10

首先,我建议您创建一个管理器文件。

First of all I suggest you to create a manager file.

import Foundation

class CollectionViewManager: NSObject {

  public var cells: [CellModel] = []

  override init() {
      super.init()

      fillCells()
 }

  fileprivate func fillCells() {
      let arrayCellModels: [CellModel] = [
          RowModel(type: .cellOne, title: "My First Cell"),
          RowModel(type: .cellTwo, title: "My Second Cell"),
          RowModel(type: .cellThree, title: "My Third Cell")
      ]

      arrayCellModels.forEach { (cell) in
          cells.append(cell)
      }
  }

}

protocol CellModel {
  var type: CellTypes { get }
  var title: String { get }
}

enum CellTypes {
  case cellOne
  case cellTwo
  case cellThree
}

struct RowModel: CellModel {
  var type: OptionsCellTypes
  var title: String

  init(type: CellTypes, title: String) {
      self.type = type
      self.title = title
  }

}

之后,您应该在ViewController中初始化您的经理。

After that in your ViewController you should initialise your manager. Something like that.

class ViewController: UICollectionViewController {

  let collectionViewManager = CollectionViewManager()

  // your code here
}

接下来,您进行一个ViewController扩展

Next you make an ViewController extension.

extension ViewController: UICollectionViewDelegateFlowLayout {

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // number of items from your array of models
    return collectionViewManager.cells.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // init item
    let item = collectionViewManager.cells[indexPath.item]

    // than just switch your cells by type 
    switch item.type {
    case .cellOne:
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CellOne.self), for: indexPath) as! CellOne {
        cell.backgroundColor = .red
        return cell
    case .cellTwo:
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CellTwo.self), for: indexPath) as! CellTwo {
        cell.backgroundColor = .blue
        return cell
    case .cellThree
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CellThree.self), for: indexPath) as! CellThree {
        cell.backgroundColor = .yellow
        return cell
        }
}

}