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



我正在尝试创建一个数组,该数组包含我要取消的自定义集合视图单元格的类。下面我提供了一个示例,说明我想如何使用这个数组。cellType是一个保存我想去的类的变量,cellClass是一个包含不同类的数组。我见过与此类似的问题,但所有答案似乎都建议使用类的实例,例如 className.self。是否可以创建这样的数组。谢谢。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellType = cellClass[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! cellType
cell.addRemoveCellDelegate = self
cell.label.text = "(indexPath)"
switch indexPath.item {
case 0:
cell.backgroundColor = .magenta
cell.screenLabel.text = screens[0]
case 1:
cell.backgroundColor = .purple
cell.screenLabel.text = screens[1]
case 2:
cell.backgroundColor = .yellow
cell.screenLabel.text = screens[2]
case 3:
cell.backgroundColor = .green
cell.screenLabel.text = screens[3]
default:
cell.backgroundColor = .blue
}
return cell
}

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

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

之后,在视图控制器中,您应该初始化管理器。类似的东西。

class ViewController: UICollectionViewController {
let collectionViewManager = CollectionViewManager()
// your code here
}

接下来,您创建一个视图控制器扩展。

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

最新更新