使用RxSwift重新加载Tableview

问题描述 投票:3回答:3

我正在使用RxSwift进行tableview。每次从api获取数据后我都需要重新加载我的表但是我没有这样做。我找不到任何解决方案。有人可以帮忙吗?

我有一个从Api的响应获得的地方数组。我在视图中使用了这个代码加载,但是在更新数组时它没有被调用。

enter image description here

ios swift rx-swift rx-cocoa
3个回答
8
投票

我发现了这个问题。我的阵列没有正确更新。我做了以下更改。

声明ModelClass的dataSource变量:

let dataSource = Variable<[SearchResult]>([])

现在将它与表视图绑定为空:

dataSource.asObservable().bindTo(ResultsTable.rx.items(cellIdentifier: "SearchCell")){ row,Searchplace,cell in
    if let C_cell = cell as? SearchTableViewCell{
        C_cell.LocationLabel.text = Searchplace.place
    }
}.addDisposableTo(disposeBag)

然后将包含searchPlaces的更新数组存储在其中:

dataSource.value = self.array

现在,每次更改dataSource的值时,将重新加载表视图。


3
投票

避免使用“变量”,因为此概念将从RxSwift弃用,但官方迁移路径尚未确定。

REF:https://github.com/ReactiveX/RxSwift/issues/1501

因此,建议使用RxCocoa.BehaviorRelay。

let dataSource = BehaviorRelay(value: [SearchResultModel]())

绑定到tableView

 self.dataSource.bind(to: self.tableView.rx.items(cellIdentifier: "SearchCell", cellType: SearchCell.self)) { index, model, cell in
      cell.setupCell(model: model)
 }.disposed(by: self.disposeBag)

获取数据后:

let newSearchResultModels: [SearchResultModel] = ..... //your new data
dataSource.accept(newSearchResultModels)

希望这可以帮助:)


2
投票

array = Variable<[SearchResult]>([])

每当您点击API时,将获取的结果放在self.array.value中,它将自动更新。

 self.array.asObservable().bindTo(ResultsTable.rx.items(cellIdentifier: "SearchCell", cellType:SearchCell.self)) 
   { (row, element, cell) in
        cell.configureCell(element: element)
   }.addDisposableTo(disposeBag)
© www.soinside.com 2019 - 2024. All rights reserved.