从UITableView转发ControlEvent

时间:2017-03-31 10:12:23

标签: ios swift uitableview rx-swift

我想在一个单独的控制器中创建一个行星列表(我的PlanetPickerViewController)。此控制器使用UITableView显示Planet的给定列表。这很好。

public class PlanetPickerViewController: RxViewController {

    // MARK: - PUBLIC -

    public var selection: ControlEvent<Planet>!

    public init(list: Driver<[Planet]>, active: Planet?) {
        self.list = list
        self.active = active
        super.init(nibName: "PlanetPickerViewController", bundle: nil)
    }

    @available(*, unavailable)
    required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }

    // MARK: - PRIVATE -

    private let list: Driver<[Planet]>
    private let active: Planet?

    // MARK: IBOutlets

    @IBOutlet private weak var tableView: UITableView!

    // MARK: View life cycle

    override public func viewDidLoad() {
        super.viewDidLoad()
        self.initializeTableView()
    }

    private func initializeTableView() {
        self.list.drive(self.tableView.rx.items(reusable: PlanetTableViewCell.self)) { row, planet, cell in
            cell.display(planet)
            cell.isSelected = planet == self.active
        }
        .disposed(by: self)

        self.selection = self.tableView.rx.modelSelected(Planet.self)
    }
}

现在我想转发用户点击单元格的事件。通常,我会创建一个PlanetPickerViewControllerDelegate,其中包含专门的功能来手动转发此事件:

// PlanetPickerViewControllerDelegate
picker(_ picker: PlanetPickerViewController, didSelect planet: Planet)

// PlanetPickerViewController: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let planet = self.list[indexPath.row]
    self.delegate?.picker(self, didSelect: planet)
}

但是对于RxSwift,我想用ControlEvent<Planet>替换这个委托。这就是我对public var selection: ControlEvent<Planet>!的意图。不好的是我在viewDidLoad发生之前无法订阅它......

如果实例化此控制器,我应该更改哪些能够订阅我的selection

let modal = PlanetPickerViewController(list: planets, active: nil)
modal.selection.subscribe { do something }
self.present(modal, animated: true, completion: nil)

1 个答案:

答案 0 :(得分:0)

您可以在主视图控制器中创建Observable<Planet>并订阅它:

// PlanetPickerViewController

let didSelectPlanet: Observable<Planet>!

private func initializeTableView() {
    // ...

    self.didSelectPlanet = self.tableView.rx.modelSelected(Planet.self).asObservable()
}


// MainViewController
let modal = PlanetPickerViewController(list: planets, active: nil)
modal.self.didSelectPlanet
     .subscribe(onNext: { _ in /* do something */ })
     .disposed(by: disposeBag)