RxSwift和UICollectionView,UITableView

jon*_*ren 0 ios uicollectionview swift rx-swift rxdatasources

我有一个问题:如何使用RxDataSources以Rx方式正确实现这样的场景:

我们有一个带有UICollectionView(或UITableView,在我的情况下是它的集合视图)的类,结果不会立即出现,它们会在一段时间后异步出现.

我已根据本教程中的部分实现了我的模型: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)
Run Code Online (Sandbox Code Playgroud)

如果我的项目在一段时间后可用,我希望我的集合视图能够自动更新,该怎么办?

谢谢你的帮助.

bee*_*ven 6

你可以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()
    }
}
Run Code Online (Sandbox Code Playgroud)

当您更改时,UI将自动更新sections.value.

希望这可以帮到你.