【问题标题】:RxSwift and UICollectionView, UITableViewRxSwift 和 UICollectionView、UITableView
【发布时间】:2017-01-13 12:41:53
【问题描述】:

我有一个问题:如何使用 RxDataSources 在 Rx-way 中正确实现这样的场景:

我们有一个带有 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)

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

感谢您的帮助。

【问题讨论】:

    标签: ios swift uicollectionview rx-swift rxdatasources


    【解决方案1】:

    你可以像这样使用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 会自动更新。

    希望对您有所帮助。

    【讨论】:

    • 使用Variable 并不是解决问题的一种特别被动的方式,因为现在您已经再次创建了一个有状态的环境。最好听一个tap 事件并相应地定义sections 变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    相关资源
    最近更新 更多