4

我有一个表格视图,我从视图模型中填充一些数据,我正在使用 RxSwift 和 RxDataSources ...我有下一个代码

  enum TableViewEditingCommand {
    case DeleteItem(IndexPath)
  }

struct SectionedTableViewState {
    fileprivate var sections: [MySectionViewModel]

    init(sections: [MySectionViewModel]) {
        self.sections = sections
    }

    func execute(command: TableViewEditingCommand) -> SectionedTableViewState {
        switch command {

        case .DeleteItem(let indexPath):

            var sections = self.sections
            var items = sections[indexPath.section].items

            items.remove(at: indexPath.row)
            sections[indexPath.section] = MySectionViewModel(original: sections[indexPath.section], items: items)
            return SectionedTableViewState(sections: sections)
        }
    }
}

我的视图控制器有这样的东西

    class MyViewController : UIViewController { 
       let dataSource = RxTableViewSectionedAnimatedDataSource<MySectionViewModel>()

      override func viewDidLoad() {
            super.viewDidLoad() 

       viewModel.findElements()
                .bindTo(tableView.rx.items(dataSource:dataSource))
                .addDisposableTo(disposeBag)

     dataSource.configureCell = { datasource, tableView, indexPath, item in
         .... my configuration
      }

  dataSource.canEditRowAtIndexPath = { _ in true}

  let deleteCommand = tableView.rx.itemDeleted.asObservable()
            .map(TableViewEditingCommand.DeleteItem)

  let initialState = SectionedTableViewState(sections:dataSource.sectionModels)

Observable.of(deleteCommand)
            .merge()
            .scan(initialState) { (state: SectionedTableViewState, command: TableViewEditingCommand) -> SectionedTableViewState in
                return state.execute(command: command)
            }
            .startWith(initialState)
            .map {
                $0.sections
            }
            .shareReplay(1)
            .bindTo(tableView.rx.items(dataSource: dataSource))
            .addDisposableTo(disposeBag)


}



    }

好像在这一行

let initialState = SectionedTableViewState(sections:dataSource.sectionModels)

section 是一个空数组,因为我得到一个索引超出范围异常,并且当我打印数组时,它没有任何元素。我的问题是如何从数据源中获取部分?

我从这个网址看到了这个例子: https ://github.com/RxSwiftCommunity/RxDataSources/blob/master/Example/Example3_TableViewEditing.swift

提前致谢。

4

0 回答 0