[英]RxSwift and UICollectionView, UITableView
I have a question: how to properly implement such a scenario in Rx-way with RxDataSources: 我有一个问题:如何使用RxDataSources在Rx方式中正确实现这样的方案:
We have a class with UICollectionView (or UITableView, in my case it's collection view), the results are not immediately present, they come asynchronously after some time. 我们有一个带有UICollectionView(或UITableView,在我的例子中是集合视图)的类,结果不会立即显示出来,它们在一段时间后异步出现。
I have implemented my model with sections according to the tutorial here: https://github.com/RxSwiftCommunity/RxDataSources 我已经根据此处的教程按部分实现了我的模型: https : //github.com/RxSwiftCommunity/RxDataSources
But the data is created only once with just
there: 但是仅
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)
What to do in case my items are available after some time and I want my collection view to be updated automatically? 如果我的物品在一段时间后可用并且我希望我的收藏夹视图自动更新怎么办?
Thanks for any help. 谢谢你的帮助。
You can use Variable<[Section]>
like this: 您可以像这样使用
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()
}
}
The UI will update automatically when you change sections.value
. 当您更改
sections.value
时,UI将自动更新。
Hope this may help you. 希望这对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.