RxSwift和UICollectionView,UITableView

时间:2017-01-13 12:41:53

标签: ios swift uicollectionview 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)

如果我的商品在一段时间后可用,我希望我的收藏视图能够自动更新,该怎么办?

感谢您的帮助。

1 个答案:

答案 0 :(得分: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()
    }
}

当您更改sections.value时,用户界面会自动更新。

希望这可以帮助你。