gpt4 book ai didi

ios - Swift DRY collectionView(_ cellForItemAt) 调用

转载 作者:行者123 更新时间:2023-11-29 00:02:46 26 4
gpt4 key购买 nike

当我有不同类型的单元格时,我发现自己经常执行这些重复的代码。有没有办法把它弄干?或者它是否尽可能好。

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch cells[indexPath.item].type {
case .aCell:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ACellID, for: indexPath) as! ACell
cell.data = somedata
return cell
case .bCell:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BCellID, for: indexPath) as! BCell
cell.data = somedata
return cell
case .cCell:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CCellID, for: indexPath) as! CCell
cell.data = somedata
return cell
}
}

我正在考虑让所有单元采用协议(protocol)并将它们放入数组中

最佳答案

据我了解,您可以使用所有单元格都可以遵守的协议(protocol),并扩展您的单元格类型枚举以返回单元格 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
}

}

关于ios - Swift DRY collectionView(_ cellForItemAt) 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49016062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com