ios - Swift DRY collectionView(_ cellForItemAt) 调用

标签 ios uicollectionview swift4

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

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/

相关文章:

ios - 扩展 UIPickerView 以更改标题颜色

ios - Firebase 不会跳入方法内部

ios - Swift 4 MKMapView 像 GoogleMap 一样改变 map 样式

ios - 在 FBSDKShare 对话框中共享多个图像

ios - 添加启动屏幕会更改我整个应用程序的显示

iphone - UICollectionView 内容在 reloadData 后被隐藏

ios - UICollectionView 部分标题闪烁问题

ios - 对 UICollectionView 中的特定单元格进行动画处理

swift - 在 Swift 中,如何在对象创建后立即调用函数

ios - 移至自定义 UItableViewCell 中的下一个 UItextfield(具有多个部分的 Tableview)