我如何制作一个保存类型的数组?

时间:2018-08-23 03:28:29

标签: ios arrays swift types casting

我正在尝试创建一个数组,该数组包含我要出队的自定义collectionView单元的类。下面提供了一个有关如何使用此数组的示例。 centralWidget()->setMaximumHeight(0); 是一个变量,它包含我要出队列的类,而cellType是一个数组,其包含不同的类。我已经看到类似的问题,但是所有答案似乎都建议使用类的实例,例如className.self。是否可以创建这样的数组。谢谢。

cellClass

1 个答案:

答案 0 :(得分:2)

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

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中初始化您的经理。这样的事情。

class ViewController: UICollectionViewController {

  let collectionViewManager = CollectionViewManager()

  // your code here
}

接下来,您将进行ViewController扩展。

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

}
相关问题