RxSwift和UIPickerView

时间:2017-02-17 18:36:08

标签: ios swift uipickerview rx-swift rx-cocoa

有没有办法将UIPickerView与Observable绑定?

例如对于UITableView,我会这样做:

myObservableArray.bindTo(tableView.rx.items(cellIdentifier: "Identifier", cellType: MyCustomTableViewCell.self)) { (row, title, cell) in
        cell.textLabel?.text = title
    }
    .disposed(by: disposeBag)

UIPickerView是否有类似内容?

2 个答案:

答案 0 :(得分:1)

事实上,RxCocoa库中有:

示例:

let items = Observable.just([
        "First Item",
        "Second Item",
        "Third Item"
    ])

items
    .bind(to: pickerView.rx.itemTitles) { (row, element) in
        return element.title
    }
    .disposed(by: disposeBag)

还有:

items
   .bind(to: pickerView.rx.items) { (row, element, view) in
       guard let myView = view as? MyView else {
           let view = MyView()
           view.configure(with: element)
           return view
       }
       myView.configure(with: element)
       return myView
   }
   .disposed(by: disposeBag)

答案 1 :(得分:0)

提供的选择器数据源如下所示:

let pickerDataSource: [[String]] = [ ["asdadadad", "sffgddfg"],
                                     ["sfsdasgag", "sdfasdfasfsf", "sdsfgagagaggs"] ]

你可以用这种方式实现你需要的“绑定”:

pickerView.rx.itemSelected.subscribe(onNext: { [weak self] row, component in
    guard let s = self else { return }
    s.label.text = s.pickerDataSource[component][row]
}).addDisposableTo(disposeBag)