Theo Kallioras
Theo Kallioras

Reputation: 3676

RxSwift and UIPickerView

Is there a way to bind a UIPickerView with an Observable?

For example for a UITableView I would do:

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

Is there something similar for UIPickerView ?

Upvotes: 6

Views: 3637

Answers (2)

Daniel T.
Daniel T.

Reputation: 33979

As a matter of fact there is, in the RxCocoa library:

Example:

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

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

There's also:

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)

Upvotes: 2

Valeriy Van
Valeriy Van

Reputation: 1865

Provided data source of your picker looks like this:

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

you could implement 'binding' you need in this way:

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)

Upvotes: 0

Related Questions