Swift DRY collectionView(_ cellForItemAt)调用

时间:2018-02-27 18:58:01

标签: ios uicollectionview swift4

当我有不同类型的细胞时,我发现自己做了很多重复的代码。有没有办法让它干涸?或者它是否尽可能好。

protocol

我想让所有单元格都采用{{1}}并将它们放在一个数组中

2 个答案:

答案 0 :(得分:1)

根据我的理解,您可以使用您的所有单元格可以符合的协议,并扩展您的单元格类型枚举以返回单元格ID,这样您就不需要每次都要切换出队。

enum CellType {
    case aCell, bCell, cCell

    var id: String {
        switch self {
        case .aCell: return "aCellId"
        case .bCell: return "bCellId"
        case .cCell: return "cCellId"
        }
    }
}

protocol CellData {

    // Remove since you probably have your modlue type.
    typealias Module = String

    var type: CellType { get }
    var modlues: [Module] { get } // Module type
}

protocol CommonCellProperty: AnyObject {
    var data: CellData! { get }
}

typealias CommonCell = CommonCellProperty & UICollectionViewCell

class MasterCell: UICollectionViewCell, CommonCellProperty {
    var data: CellData! // set data
}
class HolderCell: UICollectionViewCell, CommonCellProperty {
    var data: CellData! // set data
}
//...

class ViewController: UIViewController, UICollectionViewDataSource {

    var cells: [CellData] = []

    override func viewDidLoad() {
        super.viewDidLoad()

    }

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

        let cellData: CellData = cells[indexPath.section]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellData.type.id, for: indexPath) as! CommonCell

        //cell.data = somedata

        return cell
    }

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

}

答案 1 :(得分:0)

是的,如果这真的是你的代码模式,唯一不同的是标识符,我建议创建一个字典,其中键是单元格类型,值是标识符

//Create a dictionary to map from cell type to identifier
let cellIDs = [
  .aCell: ACellID,
  .bCell: BCellID,
  .cCell: CCellID
]

//Define a common class for the different cell types
class MyCell: UICollectionViewViewCell {
  var data: Data
}


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

  let cell: MyCell
  let cellType = cells[indexPath.item].type
  let cellIdentifier = cellIDs[cellType]
  cell = collectionView.dequeueReusableCell(
    withReuseIdentifier: 
    cellIdentifier, 
    for: indexPath) as! MyCell
  cell.data = someData
  return cell
}

或者,将另一个字段identifier添加到包含每个单元格类型的数组cells,然后只需从您的数组中获取单元格的重用标识符,就像您当前一样使用细胞类型。