9
6

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 5 years have passed since last update.

【Swift】複数の picker がある pickerView で二次元配列を使う。

Last updated at Posted at 2019-02-24

以前、
【Swift】複数のsectionがあるtableViewで二次元配列を使う。
というタイトルで投稿しました。
今回は、複数の picker がある pickerView で二次元配列を使ってみました。
MultiPickers.gif
上図のように3年A組~C組の3つのピッカーに複数の生徒の row があります。
二次元配列を twoDimArray とします。
3年A組のピッカーを「myPickerA」、tag = 0
3年B組のピッカーを「myPickerB」、tag = 1
3年C組のピッカーを「myPickerC」、tag = 2
一番下の「井上 鈴木 遠藤」というラベルを「myLabel」とします。
このサンプルを使えば、picker や row がいくら増えても「func numberOfComponents~」以下のコードを一文字も書き換える必要がありません。

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    
    @IBOutlet var myPickerA:UIPickerView!
    @IBOutlet var myPickerB:UIPickerView!
    @IBOutlet var myPickerC:UIPickerView!
    @IBOutlet var myLabel:UILabel!
    
    var twoDimArray = [[String]]()
    var selectedPerson = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        for _ in 0 ... 2{
            twoDimArray.append([])
        }
        twoDimArray[0] = ["井上","加藤","田中"]
        twoDimArray[1] = ["鈴木","吉田"]
        twoDimArray[2] = ["遠藤","佐藤","村田","山田"]
        
        selectedPerson = ["井上","鈴木","遠藤"]
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        return twoDimArray[pickerView.tag].count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
        return twoDimArray[pickerView.tag][row]
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectedPerson[pickerView.tag] = twoDimArray[pickerView.tag][row]
        var labelText = ""
        for i in selectedPerson{
            labelText += "\(i)  "
        }
        myLabel.text = labelText
    }
}
9
6
2

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
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?