Add UIPickerView to ViewController in Swift

Posted by
  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() {
        super.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

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Google photo

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

Twitter picture

You are commenting using your Twitter 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.