Easy UIPickerView with RxSwift & RxCocoa Magic

RxSwift (and RxCocoa) make it super easy to wire up a UIPickerView for your IOS project. No need to bother with the UIPickerViewDataSource and Delegate protocols and the attendant methods that you would normally be required to implement. Instead, it can be as simple as this in your viewcontroller:

import UIKit
import RxSwift
import RxCocoa

class MyViewController: UIViewController {

  // MARK: – Variables
let
disposeBag = DisposeBag()
var pickerView = UIPickerView()

  override func viewDidLoad() {
    super.viewDidLoad()
    setupRx()
}

func setupRx() {

        //#1 bind your data to pickerview
Observable.just([“Item 1″,”Item 2”, “etc”])
                             .bind(to: pickerView.rx.itemTitles) { _, item in
                return \(item)”
         }.disposed(by: disposeBag)

        //#2 handle pickerview selection
pickerView.rx.itemSelected.asObservable().subscribe(onNext: {item in

            //item.row gives you the index of the selected item, so do what you need with                  it

            //also here you can call .resignFirstResponder() on whatever element brought up the pickerview (e.g. a button) in order to close the pickerview

        }).disposed(by: disposeBag)

        //optional: preselect the second item in pickerview
pickerView.selectRow(1, inComponent: 0, animated: true)

}

} //end class

So what’s going on?

In #1, we bind our data to the pickerview. In the example we simply have a small array of some strings to display. This could instead come from coredata, over the network, or whatever your app requires.

In #2, we set up the subscription to observe selections made on the pickerview. In the closure’s body you can put whatever business logic you need to handle the selection, with “item.row” giving you the index of the selected item from the array. You would also call resignFirstResponder() here in most cases in order to close the pickView.

And that’s it! Neat huh?

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s