This is the final lesson in the Swift Picker View tutorial series and in it you learn how to do the following:

  • Configure the pickerView to display two components.
  • Preselect a row to display in the pickerView components’ selection indicators.
  • Display objects of the itemNameList array in the first component rows.
  • Display objects of the itemPhotoList in the second component rows.
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.

The first thing you have to do is configure the pickerView to display two components, instead of one, in the pickerView.

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

Next, preselect a row to display in the pickerView components’ selection indicators.

override func viewDidLoad() {
  super.viewDidLoad()pickerView.selectRow(1, inComponent: 0, animated: true)
  ...
  pickerView.selectRow(1, inComponent: 0, animated: true)
  pickerView.selectRow(1, inComponent: 1, animated: true)
  self.selectedItemName = "Wine Glass"
  textView.text = "Item selected, \(selectedItemName)"
}

Next, modify the pickerView’s reusingView() function so it display objects of the itemNameList array in the first component rows. Display objects of the itemPhotoList array in the second component rows.

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(77, 15, 30, 30))
  let labelView = UILabel(frame: CGRectMake(0, 15, 105, 32))
        
  if component == 0 {
    imageView.image = itemPhotoList[row]
  } else {
    labelView.text = itemNameList[row]
  }
        
  view.addSubview(imageView)
  view.addSubview(labelView)
        
  return view
}

Above code will generate this output on the sim’s screen.

Figure 3-1

Figure 3-1

This conclude the Swift Picker View tutorial series. Comments are welcome! 🙂

Tags:

No responses yet

Leave a Reply

UIDocument Demystified: A Step-by-step Guide on Local and iCloud Document Storage

 

Archives