我有一个问题:如何使用 RxDataSources 在 Rx 方式中正确实现这样的场景:
我们有一个带有 UICollectionView(或 UITableView,在我的例子中是 Collection View )的类,结果不会立即出现,它们会在一段时间后异步出现。
我已经根据此处的教程实现了带有部分的模型: https://github.com/RxSwiftCommunity/RxDataSources
但是数据只创建一次,just
在那里:
let sections = [
SectionOfCustomData(header: "First section", items: [CustomData(anInt: 0, aString: "zero", aCGPoint: CGPoint.zero), CustomData(anInt: 1, aString: "one", aCGPoint: CGPoint(x: 1, y: 1)) ]),
SectionOfCustomData(header: "Second section", items: [CustomData(anInt: 2, aString: "two", aCGPoint: CGPoint(x: 2, y: 2)), CustomData(anInt: 3, aString: "three", aCGPoint: CGPoint(x: 3, y: 3)) ])
]
Observable.just(sections)
.bindTo(collectionView.rx.items(dataSource: dataSource))
.addDisposableTo(disposeBag)
如果我的项目在一段时间后可用并且我希望自动更新我的收藏 View 怎么办?
感谢您的帮助。
最佳答案
您可以使用 Variable<[Section]>
像这样:
enum Api {
/// Network response
static func call() -> Observable<[CustomData]> {
return .just([CustomData(anInt: 0)])
}
}
struct CustomData {
let anInt: Int
}
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
typealias Section = SectionModel<String, CustomData>
private let sections = Variable<[Section]>([])
private let dataSource = RxTableViewSectionedReloadDataSource<Section>()
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// change sections by api call
Api.call()
.map { (customDatas) -> [Section] in
[Section(model: "First section", items: customDatas)]
}.bindTo(sections)
.addDisposableTo(disposeBag)
sections.asDriver()
.drive(tableView.rx.items(dataSource: dataSource))
.addDisposableTo(disposeBag)
}
@IBAction func removeLastTableViewSection() {
// or you can change the sections manually.
sections.value.removeLast()
}
}
当您更改 sections.value
时,UI 将自动更新.
希望对您有所帮助。
关于ios - RxSwift 和 UICollectionView、UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41634912/