In this three part tutorial series, you learned how to use the iOS pickerView control using the Swift Programming. An Objective-C version of this tutorial series can be accessed here.
Before we begin, I assume the following:
You’ve read the Objective-C version of this tutorial.
You already know how to use Xcode IDE.
You aren’t a newbie to the Swift Programming Language
Download The PickerView Project
I’ve already created an Xcode project you will use throughout this tutorial series, so click this image to download.
When you finish unzipping the file, move it to the Interactive Swift Programming folder on your iMac.
Code presented on this page assume you are using Xcode 6.4 and Swift version 1.2. So if you are using a newer version of Swift, it may produce errors. Fix them by using Xcode’s Fix-it tool.
Launch the Swift Picker View project in Xcode. Now, there’s only one scene and class file in the project and the image below shows what they look like in Xcode IDE. The image also shows connection made for the pickerView and the textView.
When you run the Swift Picker View project in the iPhone 4s Simulator, the storyboard’s View Controller scene will look like this:
Populate The PickerView Rows
The first thing you have to do is enter code in the ViewController.swift file to populate the pickerView rows with string objects. In oreder to do that enter code shown below in the ViewController.swift file.
Code you entered in the viewDidLoad() function populate the pickerView’s data source array with eight string objects. Code you entered in the pickerView’s titleForRow() function populate the pickerView rows with string objects you entered in the pickerView’s data source, which is an array called itemNameList.
Run the app on the iPhone 4s Simulator and you will see this output on the screen:
Display The Selected Item in The textView
When the user select an item in the pickerView, the app should display it in the textView. To implement this feature in the Swift Picker View project, you’ll have to add code shown below in the pickerView’s didSelectRow() function.
Here’s output you’ll see on the sim’s screen when you select an item from the pickerView.
Preselect a Row in The PickerView
Wouldn’t be nice to preselect a row in the pickerView control and display its data in the textView control. Here’s code to implement that feature in the Picker View project and results the code will produce on the iPhone Simulator’s screen.
That’s pretty much all for today. Next week, I bring you the second part of the Swift Picker View tutorial. In the mean time comments are welcomed!
About The Author
The App Lady
I am a stay home mom. I have two amazing children and a husband who adores me. My husband was the one who got the idea for me to learn how to create "iPhone apps" and share what I'm learning with you.