我在RxSwift
上使用UICollectionView
的单元动画存在问题,我的简单设置如下:
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()!)])])
}
问题是集合视图does动画,但是看起来总是使用淡入淡出样式动画。在上面的示例中选择其他选项,例如.bottom
,仍然会产生相同的淡入淡出动画。我以前在表视图上使用过类似的逻辑,并且没有问题,我似乎只在集合视图中有问题。如何使不同样式的动画起作用?
UICollectionView
]插入/删除动画由布局处理,因此RxCollectionViewSectionedAnimatedDataSource
无法为您完成此操作。例如,如果看一下insertRows
/ insertItems
函数,您会注意到UITableView
需要动画,而UITableView
不需要动画。您看到的是UICollectionView
使用的默认动画,它是淡入淡出的动画。如果要自定义行为,则必须创建一个布局子类,为此,有很多UICollectionView
。