Categories: Swift

【Swift】UIPickerViewを使ってみる

選択肢の中から選択したりするために利用するUIPickerViewの使い方

UIPickerViewはこんなやつ

基本的な使い方

コードのみで設置からDelegateを使って選択されたものをLabelに表示します

レイアウトもコードのみなのでコピペでそのまま利用できます

import UIKit

class ViewController: UIViewController , UIPickerViewDelegate , UIPickerViewDataSource {

    var label:UILabel!
    var picker:UIPickerView!
    var items:[String] = [
        "item1",
        "item2",
        "item3",
        "item4",
        "item5",
    ]
    
    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 1
    }
    
    //列あたりの数を設定
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return items.count
    }
    
    //列に設定する文字列
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return items[row]
    }
    
    //選択されたときの動作
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.label.text = items[row]
    }
}

動作は下記の動画を確認してください

Pype