【问题标题】:RxSwift 3.1 UITableView data source not workingRxSwift 3.1 UITableView 数据源不工作
【发布时间】:2016-12-29 15:23:03
【问题描述】:

我在我的新项目中通过 Carthage 使用 RxSwift 3.1 (Galois),我刚刚尝试使用我在网上和文档中找到的一些示例将数据绑定到 UITableView - 其中一个是这个文件: https://github.com/ReactiveX/RxSwift/blob/master/RxExample/RxExample/Examples/SimpleTableViewExample/SimpleTableViewExampleViewController.swift

我的代码现在看起来像这样(我已经尝试过简化它,因为我想要的工作没有):

class ChooseCityView: UIViewController, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {

        super.viewDidLoad()

        let dataSource = Observable.just((0..<20).map { "\($0)" })
        let disposeBag = DisposeBag()

            dataSource.bindTo(tableView.rx.items(cellIdentifier: "CityCell", cellType: UITableViewCell.self)) {
                (row, city, cell) in
                cell.backgroundColor = .white
                cell.textLabel?.text = "test \(city)"
            }.addDisposableTo(disposeBag)

        // Remove empty cells
        tableView.tableFooterView = UIView()

    }
}

不过,在模拟器中运行应用程序后,它不会显示任何行。我在 tableView 上有一个名为“CityCell”的原型单元格,类型为 Basic。另外,我确保插座与实际的 tableView 绑定。我可能做错了什么?或者这是一个错误?

提前致谢:)

【问题讨论】:

  • 您的示例无法构建,dataSource has no member bindTo
  • 代码编译并运行,这与示例中指定的相同 - 我使用的是 Observer.just 它返回一个 ObservableType,它具有 bindTo 方法
  • 问题是运行后表格没有反映数据源的单元格
  • 抱歉,我忘记添加 RxCocoa 的导入。

标签: ios swift xcode rx-swift reactivex


【解决方案1】:

一段时间后,我找到了解决方案。添加disposeBag 作为视图控制器的属性。对于您的代码:

class ChooseCityView: UIViewController, UITableViewDelegate  {

    @IBOutlet weak var tableView: UITableView!
    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        let dataSource = Observable.just((0..<20).map { "\($0)" })

        dataSource.bindTo(tableView.rx.items(cellIdentifier: "CityCell", cellType: UITableViewCell.self)) {
            (row, city, cell) in
            cell.backgroundColor = .white
            cell.textLabel?.text = "test \(city)"
            }.addDisposableTo(disposeBag)

        // Remove empty cells
        tableView.tableFooterView = UIView()
    }
}

【讨论】:

  • 哇,这真的有效!我已经像其他所有东西一样尝试了几个小时......我永远不会猜到这可能是问题:) 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2012-06-25
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多