【问题标题】:RXSwift - RxCollectionViewSectionedReloadDataSource - Drag & drop move (Reorder)RXSwift - RxCollectionViewSectionedReloadDataSource - 拖放移动(重新排序)
【发布时间】:2021-11-26 07:59:40
【问题描述】:

我使用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)

使用上面的代码我可以显示数据。但我想拖放(重新排序)单元格。

请告诉我如何使用RxSwift 重新排序。

我们将不胜感激。

【问题讨论】:

    标签: ios xcode uicollectionview rx-swift


    【解决方案1】:

    通常情况下,您需要一个状态机。

    涉及的逻辑很简单:

    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)
        }
    }
    

    以上使用 RxCocoa 提供的ItemMovedEvent 用于表视图。为了为集合视图创建类似的东西,您需要将UICollectionViewDragDelegate 包装在委托代理中。一篇关于如何做到这一点的文章可以在这里找到:Convert a Swift Delegate to RxSwift Observables

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 2013-05-11
      • 2012-05-31
      相关资源
      最近更新 更多