UIPickerview as inputview to uitextfield in swift


This tutorial is updated for X code 7.3 & swift 2.2

This is very commonly used in many iOS apps. Instead of keyboard popping up when you click on text field, the picker view pops up. And you can select one or multiple strings to be added to the textfield.

  1. First lets set up the x code project as usual. Create new single view application X code project. Set project name to picker textfield demo & save it on desktop.

new x code project


2. Go to main storyboard and select view controller. Set its size to iPhone 4 inch

iPhone size 4 inches


3. Add textfield to view controller & set it’s width to 150

add textfield


4. Add label to view controller & set it’s text to Select one option

add label


5. Connect textfield to view controller swift file

add textfield as outlet


6. Create array to store all picker view options just before view did load

var pickOption = ["one", "two", "three", "seven", "fifteen"]

override func viewDidLoad() {

7. Create picker view in view did load as follows. You may get error but we will fix it soon

override func viewDidLoad() {

    var pickerView = UIPickerView()

    pickerView.delegate = self

    pickerTextField.inputView = pickerView

    // Do any additional setup after loading the view, typically from a nib.

8. We will add picker view datasource & delegate to view controller as follows

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

9. Set number of components in picker view

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1

10. Set number of rows in components

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return pickOption.count

11. Set title for each row

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickOption[row]

12. Update textfield text when row is selected

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    pickerTextField.text = pickOption[row]

Build and run app in iPhone 5s. Tap the textfield and select one option from picker view.
picker w 1 column
Download X code file
Challenge 1: Add bar on top of picker view with buttons & label as follows.

uitoolbar to pickerview
Download Challenge 1 Solution
Challenge 2: Show two columns in uipickerview & update textfield from strings of each column

picker w 2 column
Download Challenge 2 Solution
Challenge 3: Create multiple textfield with different pickerview for each textfield

multiple pickerview textfield
Download Challenge 3 Solution

Total 48 Votes

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?