コンテンツへスキップ

【Swift】UIPickerViewを複数列で使ってみる

一列で使うサンプルは下記をご覧ください

【Swift】UIPickerViewを使ってみる

複数列で簡単なサンプルを作ってみました

コードのみで実装

import UIKit

class ViewController: UIViewController , UIPickerViewDelegate , UIPickerViewDataSource {

    var label:UILabel!
    var picker:UIPickerView!
    var items1:[String] = [
        "1-1",
        "1-2",
        "1-3",
        "1-4",
        "1-5",
    ]
    var items2:[String] = [
        "2-1",
        "2-2",
        "2-3",
        "2-4",
        "2-5",
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.label = UILabel()
        self.label.translatesAutoresizingMaskIntoConstraints = false
        self.label.font = UIFont.systemFont(ofSize: 30)
        self.label.textAlignment = .center
        self.view.addSubview(self.label)
        
        self.label.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.label.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        self.label.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        self.label.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.5).isActive = true
               
        self.picker = UIPickerView()
        self.picker.delegate = self
        self.picker.dataSource = self
        self.picker.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(self.picker)
        
        self.picker.topAnchor.constraint(equalTo: self.label.bottomAnchor).isActive = true
        self.picker.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        self.picker.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        self.picker.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
    }
    
    //列数を設定
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 2
    }
    
    //列あたりの数を設定
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        
        switch component {
        case 0:
            return items1.count
        case 1:
            return items2.count
        default:
            return 0
        }
    }
    
    //列に設定する文字列
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        switch component {
        case 0:
            return items1[row]
        case 1:
            return items2[row]
        default:
            return ""
        }
    }
    
    //選択されたときの動作
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        switch component {
        case 0:
            self.label.text = items1[row]
        case 1:
            self.label.text = items2[row]
        default:
            return
        }
    }
}

各列毎に配列を用意して、それを表示させているだけなので簡単ですね