LoginSignup
1
1

More than 3 years have passed since last update.

UIPickerView swift

Posted at

■UIPickerViewとは

縦にスクロールして項目を選ぶやつ

スクリーンショット 2021-04-19 23.21.04.png

■基本的に2つのprotocolを記載しデリゲートメソッドを使う。

まずはUIPickerViewDatasource

extension ViewController: UIPickerViewDataSource {
    //縦の列の数を決める。
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    //行の数を決める。 基本配列の中身の数を指定
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return weatherManager.prefecturesArray.count
    }
}

次にUIPickerViewDelegate

extension ViewController: UIPickerViewDelegate {
    //配列の中身をUipickerに表示 Array[row] rowは配列の中身の数ぶん,数字が入る。配列の中身が10個なら0~9のインデックス番号
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return weatherManager.prefecturesArray[row]
    }

  //スクロールして選択 didSelectRowのrowは選択した配列の中身のインデックス番号になる。
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        let selectPrefecture = weatherManager.prefecturesArray[row]
        weatherManager.getprefecture(for: selectPrefecture)
    }
}

基本はこんな感じ

1
1
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
1
1