[英]RXSwift - RxCollectionViewSectionedReloadDataSource - Drag & drop move (Reorder)
I have used RxCollectionViewSectionedReloadDataSource
to load my data into UICollectionView
.我已经使用
RxCollectionViewSectionedReloadDataSource
将我的数据加载到UICollectionView
中。
let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, WorkGroup>>(
configureCell: { (_, collectionView, indexPath, item) in
guard let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: WorkGroupCell.identifier, for: indexPath) as? WorkGroupCell else {
return WorkGroupCell()
}
cell.viewModel = item
return cell
}
)
viewModel.items.bind(to: tileCollectonView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)
tileCollectonView.rx.setDelegate(self).disposed(by: disposeBag)
Using above code i can display the data.使用上面的代码我可以显示数据。 But i want to drag and drop(Reorder) the cell.
但我想拖放(重新排序)单元格。
Please let me know how can i do that reorder using RxSwift
.请让我知道如何使用
RxSwift
进行重新排序。
Help will be highly appreciated.帮助将不胜感激。
As is often the case, you need a state machine.通常情况下,您需要一台 state 机器。
The logic involved is quite simple:涉及的逻辑非常简单:
struct State<Item> {
var items: [Item] = []
}
func state<Item>(initialState: State<Item>, itemMoved: Observable<ItemMovedEvent>) -> Observable<State<Item>> {
itemMoved
.scan(into: initialState) { (state, itemMoved) in
state.items.move(from: itemMoved.sourceIndex.row, to: itemMoved.destinationIndex.row)
}
.startWith(initialState)
}
extension Array
{
mutating func move(from oldIndex: Index, to newIndex: Index) {
if oldIndex == newIndex { return }
if abs(newIndex - oldIndex) == 1 { return self.swapAt(oldIndex, newIndex) }
self.insert(self.remove(at: oldIndex), at: newIndex)
}
}
The above uses the ItemMovedEvent
provided by RxCocoa for table views.上面使用了 RxCocoa 提供的
ItemMovedEvent
用于表视图。 In order to create something like that for a collection view, you will need to wrap the UICollectionViewDragDelegate
in a delegate proxy.为了为集合视图创建类似的东西,您需要将
UICollectionViewDragDelegate
包装在委托代理中。 An article on how to do that can be found here: Convert a Swift Delegate to RxSwift Observables关于如何做到这一点的文章可以在这里找到: Convert a Swift Delegate to RxSwift Observables
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.