Swift Picker View Part 2

This is part 2 of the Swift Picker View tutorial and in it you learn how to do display item images and names in a single component of PickerViewHere’s what the ViewController.swift file looks like now:

Figure 2-1
Figure 2-1
caution 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.

Display Text and Images in The PickerView

As of now, the single component of the pickerView is configured to display only item names in its rows. The item names are stored in the pickerView’s data source. It is an array called, itemNameList. Now, to display item images and names in a single component of the pickerView, you’ll have to do the following in the viewController.swift file.

Declare an array variable.

 var itemPhotoList = [UIImage]()

In the viewDidLoad() function add eight image names in the itemPhotoList array.

itemPhotoList.append(UIImage(named: "87-wine-glass.png")!)
itemPhotoList.append(UIImage(named: "70-tv.png")!)
itemPhotoList.append(UIImage(named: "Jeep.png")!)
itemPhotoList.append( UIImage(named: "dog.png")!)
itemPhotoList.append(UIImage(named: "office-phone.png")!)
itemPhotoList.append(UIImage(named: "flowers-icon.png")!)
itemPhotoList.append(UIImage(named: "star.png")!)

Now, the images you added in the array are locate in the project’s Media library. To see them click the Library bar’s “Media library” button.


The next thing you have to do is, replace the pickerView’s titleForRow() function with the reusingView() function.

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
  var view = UIView(frame: CGRectMake(0, 0, 110, 60))
  let imageView = UIImageView(frame: CGRectMake(0, 15, 30, 30))
  imageView.image = itemPhotoList[row]
  let labelView = UILabel(frame: CGRectMake(40, 15, 105, 32))
  labelView.text = itemNameList[row]
  return view

Code you entered in the reusingView() function does the following:

  • Create a UIView object called view.
  • Create and initialize a UILabel object.
  • Create and initialize a UIImageView object.
  • Add add both objects on the view.
  • Return the view to the pickerView.

That’s pretty much all the modification you have to make in the viewController.swift file. So run the app in the iPhone 4s Simulator and you’ll see this output on the screen.

Figure 2-2


That’s a wrap! Next, week I will bring you part 3 of the Swift Picker View tutorial. Until then, comments are welcomed! 🙂

  • Muhammad Ishmael

    Ma’am this was pretty straight forward and very easy to implement. Thank you!