Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to realize UIPickerView with RXSwift

just like UITableView

    items.bindTo(tableView.rx.items(cellIdentifier: "cellIdentifier", cellType: AttentionTableViewCell.self)){(row,dic,cell) in
        cell.configueCell(with: dic)
    }.addDisposableTo(dispose)
like image 438
BaQiWL Avatar asked Feb 08 '17 09:02

BaQiWL


3 Answers

Maybe you just have to update your RxSwift library version. It looks like pretty much the same as UI{Table|Collection}View rx bindings. Supposing you have a data source like:

let items: Observable<[String]> = Observable.of(["Row1", "Row2", "Row3"])

To populate your UIPickerView:

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

To handle selected items:

yourPickerView.rx.itemSelected
    .subscribe { (event) in
        switch event {
        case .next(let selected):
            print("You selected #\(selected.row)")
        default:
            break
        }
    }
    .disposed(by: disposeBag)
like image 70
Lucas Fonseca Avatar answered Nov 18 '22 20:11

Lucas Fonseca


Swift4 example

Observable.just(["Yes", "No", "Maybe"])
                .bind(to: picker.rx.itemTitles) { _, item in
                    return "\(item)"
                }
                .disposed(by: disposeBag)



picker.rx.itemSelected
                .subscribe(onNext: { (row, value) in
                    NSLog("selected: \(row)")
                })
                .disposed(by: disposeBag)
like image 9
norbDEV Avatar answered Nov 18 '22 20:11

norbDEV


@IBOutlet weak var pickerView: UIPickerView!
let disposeBag = DisposeBag()

Binding an array from 1 to 12 to the pickerview.

Observable.of(Array(1...12)).bind(to: pickerView.rx.itemTitles) { (row, element) in
    return String(element)
}.disposed(by: disposeBag)

Binding the selected value to anyLabel. You can bind it accordingly.

pickerView.rx.itemSelected.asObservable().map { value in String(value.row + 1) }.bind(to: anyLabel.rx.text).disposed(by: disposeBag)
like image 1
user16402129 Avatar answered Nov 18 '22 18:11

user16402129