DEV Community

Avelyn Hyunjeong Choi
Avelyn Hyunjeong Choi

Posted on • Updated on

How to use UIPickerView with Swift

DataSource

  • Access to Data
  • How many columns do I have? func numberOfComponents(in pickerView: UIPickerView) -> Int { return .. }
  • How many rows in a column? func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{ return countries.count }

Delegate

  • response to User Event
  • Title for each row? func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return countries[row] }
  • What happens if the row is selected? func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { countryLabel.text = countries[row] }

Link the DataSource and Delegate outlets of the PickerView to the ViewController
Firstly, conform to the UIPickerViewDataSource and UIPickerViewDelegate protocols to implement PickerView

Option 1.In code

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    @IBOutlet weak var countryPicker: UIPickerView!
    @IBOutlet weak var countryLabel: UILabel!
    // Data for Picker
    var countries = ["Canada", "South Korea", "US", "UK", "China"]

    override func viewDidLoad() {
        super.viewDidLoad()

        countryPicker.dataSource = self
        countryPicker.delegate = self
    }
...
Enter fullscreen mode Exit fullscreen mode

Option 2.Select UIPickerView > connection inspector > connect both dataSource and delegate to the view controller
second option

What if I want to use 2 pickers on the same ViewController?
--> set approriate tag value to picker and use that to differentiate

Look out for the tag!
Image description

Image description

How to access the selected value on a button click
-> Use .selectedRow(inComponent: #)

    @IBAction func showPickerData(_ sender: Any) {
        let countryIndex = countryPicker.selectedRow(inComponent: 0)
        print("selected country: \(countries[countryIndex])")
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)