RxSwiftでPickerが簡単に作れる
import RxSwift
class ViewController: UIViewController {
@IBOutlet private weak var label: UILabel!
@IBOutlet private weak var textField: UITextField!
private let pickerView: UIPickerView = UIPickerView()
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
setupPicker()
bind()
}
private func setupPicker() {
textField.inputView = pickerView
let toolbar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: 50.0))
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil)
//完了ボタンを押した時の動作
doneItem.rx.tap.asDriver()
.drive(onNext: { [weak self] (_) in
self?.textField.endEditing(true)
}).disposed(by: disposeBag)
toolbar.setItems([space, doneItem], animated: true)
textField.inputAccessoryView = toolbar
}
private func bind() {
//Pickerの中に使いたい配列ーここでは1900年〜2021年を配列にしている
let years = (1900 ..< 2021).map { "\($0)" + "年" }
Observable.just(years)
.bind(to: pickerView.rx.itemTitles) { _, year in
return year
}.disposed(by: disposeBag)
pickerView.rx.modelSelected(String.self)
.map { years in
return years.first
}
.bind(to: label.rx.text)
.disposed(by: disposeBag)
//Pickerの初期値ーここでは2000年にしている
self.pickerView.selectRow(100, inComponent: 0, animated: true)
}
}