0
1

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.

【Swift5】pickerViewの1行目が選択されているのに、デバックエリアに文字が表示されない

Last updated at Posted at 2021-04-25

はじめに

pikerViewを使用し、ボタンを押すと選択された「文字が表示」されるようにしたいと思いました。
pikerViewは動かすと文字を選択できますが、起動直後の状態ではhogeList[0]を呼び出す事が出来なくて調べました。

そうしたところ思いのほか調べるのに時間が掛かったので、忘却録として残しておこうと思います。

もし間違いがある場合は優しく教えていただけると嬉しいです。

環境

Xcode12.3
Swift5.3.2
macOS Catalina 10.15.4

didSelectRowの1行目が呼ばれない

下記画像のようにボタンを押した場合「コアラ」とデバッグエリアに表示したいところ「初期値」と表示されてしまいました。
スクリーンショット 2021-04-25 15.11.07.png
↓デバッグエリア
スクリーンショット 2021-04-25 15.11.18.png

原因

ブレークポイントで調べてみたところ、didSelectRowが呼ばれていませんでした。
スクリーンショット 2021-04-25 15.40.51.png

対処

参考サイトを参考にdidSelectRowを呼び出したところ無事に表示されました。

 override func viewDidLoad() {
        super.viewDidLoad()

        hogePickerView.delegate = self
        hogePickerView.dataSource = self

        //didSelectRowの1行目を呼び出す
        pickerView(hogePickerView, didSelectRow: 0, inComponent: 0)
    }

対処後

スクリーンショット 2021-04-25 15.11.07.png

↓デバッグエリア

スクリーンショット 2021-04-25 15.38.15.png

全コード

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var hogePickerView: UIPickerView!

    var hogeString = "初期値"

    let hogeList = ["コアラ", "カンガルー", "ネコ", "イヌ", "ライオン"]

    override func viewDidLoad() {
        super.viewDidLoad()

        hogePickerView.delegate = self
        hogePickerView.dataSource = self

        //didSelectRowの1行目を呼び出す
        pickerView(hogePickerView, didSelectRow: 0, inComponent: 0)
    }

    @IBAction func hogeActionButton(_ sender: UIButton) {
        print("\(hogeString)")
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
       return hogeList.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return hogeList[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        hogeString = hogeList[row]
    }
}

参照サイト

https://developer.apple.com/documentation/uikit/uipickerviewdelegate/1614371-pickerview
https://stackoverflow.com/questions/788357/uipickerview-1st-row-selection-does-not-call-didselectrow?lq=1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?