RxDataSources 集合视图单元格始终使用淡入淡出来插入单元格动画,无法更改为不同的动画

RxDataSources collection view cell always uses fade for insert cell animation, can't change to a different animation

我在 UICollectionView 上使用 RxSwift 时遇到单元动画问题,我的简单设置如下:

collectionView.register(UINib(nibName: "CustomCollectionCell", bundle: nil), forCellWithReuseIdentifier: "cell")

let dataSource = RxCollectionViewSectionedAnimatedDataSource<SectionOfCustomDataAnimated>(
    animationConfiguration: AnimationConfiguration(insertAnimation: .bottom, reloadAnimation: .bottom, deleteAnimation: .bottom),
    configureCell: { dataSource, cv, indexPath, element in
        let cell = cv.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionCell
        cell.colorView.backgroundColor = element.color
        return cell
    })

像这样的单元格和数据模型:

struct CustomDataAnimated {
    let id: Int
    let color: UIColor
}

extension CustomDataAnimated: IdentifiableType, Equatable {
    typealias Identity = Int

    var identity: Identity {
        return id
    }
}

struct SectionOfCustomDataAnimated {
    var items: [Item]

    // Need to provide a unique id, only one section in our model
    var identity: Int {
        return 0
    }
}

extension SectionOfCustomDataAnimated: AnimatableSectionModelType {
    typealias Identity = Int
    typealias Item = CustomDataAnimated

    init(original: SectionOfCustomDataAnimated, items: [Item]) {
        self = original
        self.items = items
    }
}

我正在使用 BehaviourRelay,它会在按下 update 按钮时更新:

 private let sections = BehaviorRelay<[SectionOfCustomDataAnimated]>(
        value: [SectionOfCustomDataAnimated(items: [
            CustomDataAnimated(id: 0, color: .red),
            CustomDataAnimated(id: 1, color: .yellow)
    ])])

 @IBAction func didTapUpdate(_ sender: Any) {
        let colors: [UIColor] = [.red, .blue, .green, .purple, .orange]
        let originalColors = sections.value.first!.items
        self.sections.accept([SectionOfCustomDataAnimated(items: originalColors + [CustomDataAnimated(id: originalColors.count ,color: colors.randomElement()!)])])
    }

问题是集合视图确实动画,但它似乎总是使用淡入淡出风格的动画。选择不同的选项,例如上例中的 .bottom 仍然会产生相同的淡入淡出动画。我之前在 table 视图上使用过类似的逻辑并且没有问题,我似乎只在集合视图中有问题。我怎样才能让不同风格的动画发挥作用?

UICollectionView insertion/deletion 动画由布局处理,因此 RxCollectionViewSectionedAnimatedDataSource 无法为您完成。例如,如果您查看 insertRows/insertItems 函数,您会注意到对于 UITableView it takes animation while for UICollectionView does not. What you are seeing is the default animation used by UICollectionViewFlowLayout which is a fade animation. If you want a custom behavior you have to create a layout subclass and there are plenty of tutorials