DEV Community

Avelyn Hyunjeong Choi
Avelyn Hyunjeong Choi

Posted on • Edited 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

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay