When building my App I was faced with a problem on how to let the user enter data into a textfield that I needed in a certain format, due to the fact I had functions relying on a certain format being entered into the UITextField. My perfect solution was to use the UIPickerView kindly provided by Apple in Xcode.

An example being, I want the user to enter a name into a UITextField, I want them to enter Brian Revie and simply not brian so I provide the options they can choose from, whilst still getting the value in my UITextField.

Setting Up Our Swift Project

We first setup our project, I am creating a new Single View Application in Xcode. In the Main Storyboard, I am adding a UITextField and a Label.

The goal is when a user clicks the textfield they will be presented with a UIPickerView to make their selection, then the selection will populate the textfield.

Single View Application - UIPickerView Tutorial

Next we need to open the assistant editor to allow us to hook up our UITextField in code. go ahead and click the ‘ctrl‘ button and with your mouse, click and drag from your UITextField to your Assistant Editor, move your cursor just above the ‘ViewDidLoad‘ method and release.

Give your UITextField a name that we will reference in code then click ‘Connect‘.

in your viewController.swift file you should now see:

@IBOutlet weak var myTextfield: UITextField!

Create The Picker View

We could add a UIPickerView to the Storyboard and hook it all up that way, but we will simply generate one in our code. This way the UIPickerView will only be visible when we call it in our code, otherwise we are going to need to take care of hiding it.

In the ViewDidLoad Method, add the following line of code.

let myPicker = UIPickerView()

Connect the Picker To the TextField

Now we need to tell our UITextfield that the UIPickerView will be used as the input method when it is clicked. This is simply done by assigning the myPicker as the inputView for the myTextField.

In the ViewDidLoad Method, add the following line of code.

myTextfield.inputView = myPicker

Build And Run

Go ahead and click build and run in Xcode, now when you click your TextField, you should see your awesome new UIPickerView appear from the bottom of the screen. Pretty neat! But Wait…. it’s Empty?

Well of course it is, because we have not populated the UIPickerView with any data. so lets go ahead and do that.

UIPickerView Data

Let’s set up our UIPickerView with some Data. First we need to make some changes to our ViewController.swift file.

We have to edit our class, to conform to the UIPickerViewDataSource and UIPickerViewDelegate

Find where it says:

class ViewController: UIViewController {

and change it to:

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

Now you will soon see a red error in Swift, letting us know something is wrong, but don’t worry, it is only telling us the the current viewController file doesn’t conform to the UIPickerView Datasource.

All we need to do is add the following lines 4 functions, below our ViewDidLoad Method. Don’t worry, I will explain what each function is in a moment.


func numberOfComponents(in pickerView: UIPickerView) -> Int {
}


func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
}


func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
}


func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}

Now we need to add data to these new functions to actually make them do something!

Adding our Data to the Functions

Just above our viewDidLoad Method add the following Line:

var pickerData: [String] = [String]()

here we’re declaring a new Array instance variable to store the list of data.

now inside of our ViewDidLoad method we can set some data to an array. simply add the following line of code, this will assign the array to our pickerData Variable we just set a moment ago.

pickerData = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"]

now we can go ahead and add content to our functions we added earlier.

numberOfComponents function

The numberOfComponents function is basically how many spinning dial pickers we want to appear in our UIPickerView. so for example if you were creating a date and time picker, you would have more components, one for the time, one for the date etc. Because we will be using it for 1 piece of data, we only need 1 component, so we will be returning 1 here.


func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}

numberOfRowsInComponent function

The number of rows is how many options we want to give to the user to select from. we don’t want to use a static value here, because this could be a dynamic option, meaning it may change the amount of options in the future, so we set it to automatically count how many options we have and create that many rows, to do that we simply add:


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

titleForRow function

This is what we want the user to see, so we will be grabbing the text in our array and presenting that to the user as their options, to do that we simply add:


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

didSelectRow function

This function tells the app what to do, when an option is selected in the UIPickerView. In our case we ant to populate our UITextField with the selected option. To do this we simply add:


func pickerView( pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
myTextfield.text = pickerData[row] }

One final thing to do is tell our UIPickerView that the viewController is acting as it’s delegate, so head back up to your viewDidLoad method and inside at this line of code:

myPicker.delegate = self

Build and Run your project and now you will se the magic happen! When you click your text field to add data, your UIPickerView will appear with the data we set in our Array, Then when you select an option from the UIPickerView it will populate your TextField.

Well Done!

UIPickerView Populating UITextView

The Whole Code

Here is my entire ViewController.swift file. feel free to copy and paste into your own project.


//
// ViewController.swift
// UIPickerViewExample
//
// Created by Brian on 03/12/2017.
// Copyright © 2017 Expressive Media. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet weak var myTextfield: UITextField!

var pickerData: [String] = [String]()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let myPicker = UIPickerView()

myTextfield.inputView = myPicker

pickerData = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"]

myPicker.delegate = self
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}

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

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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
myTextfield.text = pickerData[row] }

}

Final Thoughts

You are a coding superstar! Well done if you made it through, easier than you thought? Let me know how you got in the comments below if you found this Tutorial useful, or if you just want to say hello, i’d love to hear from you.

Good luck with all your coding projects!