Add UIPickerView to ViewController in Swift

  1. Drag-drop UIPickerView component on to the View Controller.

    2. Create a Swift class and add it to the ViewController.

     3. Add the below code to the class:

 Control-drag the reference for the UIPickerView in the PickerVC class.
class PickerVC: UIViewController {
    @IBOutlet weak var categoryPicker: UIPickerView!
    var categories = ["Indian", "Mexican", "American", "Chinese"]

    override func viewDidLoad() {
        //Set the ViewController as the DataSource and Delegate    for the Category Picker.
        categoryPicker.dataSource = self
        categoryPicker.delegate = self

Implement the below functions for UIPickerViewDataSource and UIPickerViewDelegate
extension PickerVC: UIPickerViewDataSource, UIPickerViewDelegate {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return categories.count
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return categories[row]

Using Xcode Version 10.1


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.