0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RxSwiftで簡単なPickerView作り

Posted at

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)
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?