UICollectionViewDiffableDataSource 自定义子类初始化

时间:2021-03-06 02:31:55

标签: swift uicollectionview init uicollectionviewcompositionallayout uicollectionviewdiffabledatasource

所以我正在制作 UICollectionViewDiffableDataSource 的自定义子类。

我的代码如下:

class MyDiffableDataSource: UICollectionViewDiffableDataSource<String, String> {
    
    convenience required init(collectionView: UICollectionView) {
        self.init(collectionView: collectionView) { (collection, index, item) in
            if index.item % 2 == 0 {
                return self.firstCell(collection, item, index)
            } else {
                return self.secondCell(collection, item, index)
            }
        }
        self.supplementaryViewProvider = { (_, _, index) in
            return self.header(collectionView, index)
        }
    }
    
    func firstCell(_ collection: UICollectionView, _ item: String, _ index: IndexPath) -> UICollectionViewListCell {
        let cellReg = UICollectionView.CellRegistration<UICollectionViewListCell, String> { (cell, _, item) in
            var content = cell.defaultContentConfiguration()
            content.text = item
            cell.contentConfiguration = content
            cell.accessories = [.disclosureIndicator()]
        }
        return collection.dequeueConfiguredReusableCell(using: cellReg, for: index, item: item)
    }
    
    func secondCell(_ collection: UICollectionView, _ item: String, _ index: IndexPath) -> UICollectionViewListCell {
        let cellReg = UICollectionView.CellRegistration<UICollectionViewListCell, String> { (cell, _, item) in
            var content = cell.defaultContentConfiguration()
            content.text = item
            cell.contentConfiguration = content
            cell.accessories = [.checkmark()]
        }
        return collection.dequeueConfiguredReusableCell(using: cellReg, for: index, item: item)
    }
    
    func header(_ collection: UICollectionView, _ index: IndexPath) -> UICollectionReusableView {
        let headerReg = UICollectionView.SupplementaryRegistration
        <UICollectionReusableView>(elementKind: UICollectionView.elementKindSectionHeader) { (_, _, _) in }
        return collection.dequeueConfiguredReusableSupplementary(using: headerReg, for: index)
    }
}

但当然,我在 'self.init' 调用或赋值给 'self' 之前使用了 'self' 来自 Xcode 的错误。

如何仅使用 UICollectionView 参数初始化 MyDiffableDataSource 而不会出现此错误?

我知道我可以将函数 firstCell()secondCell() 设为静态,或者我可以将这两个函数的所有内容直接放在 init.d 中。但是,如果我稍后添加更多内容,那将不会很好,并且静态会阻止我访问其他非静态属性。

还有其他我可以使用的解决方案吗?

谢谢!

0 个答案:

没有答案