ios - RxSwift 和 UICollectionView、UITableView

标签 ios swift uicollectionview rx-swift rxdatasources

我有一个问题:如何使用 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/

相关文章:

ios - 如何在 Today 扩展中发送和接收数据

iOS 应用程序 : Rejected in AppStore to external testers

ios - 如何在结构中设置枚举以用作标识符来初始化自定义对象

ios - UICollectionView自定义单元格布局

swift - 将单个 UICollectionViewCell 对齐到 collectionView 的左侧

ios - 使用字符串作为名称来设置属性值

ios - 更改 MFMailComposeViewController 的工具栏颜色

ios - Linkedin API 401 [未经授权]。 (带有OAuthStarterKit的iOS)错误

c# - Xamarin.iOS 和 Swift 的互操作性

ios - UICollectionViewFlowLayout子类导致cell消失