How to create Picker programmatically from array in iOS?

iOSApps/ApplicationsMobile Development

A picker view displays one or more wheels that the user manipulates to select items. Each wheel—known as a component—has a series of indexed rows representing the selectable items.

UIPicker is one of the important components and almost used in most of the applications. You’ll see them mostly in form-based applications.

You can read more about it here: https://developer.apple.com/documentation/uikit/uipickerview

In this post, we will be seeing how to create UIPicker programmatically from and array and load array values into it.

So let’s get started,

Step 1 − Open Xcode and create a single view application and name it PickerSample.

Step 2 − Open ViewController.swift, Since we are making programmatically we won’t be touching storyboard at all.

Step 3 − First in viewDidLoad method creates an object of UIPickerView

let UIPicker: UIPickerView = UIPickerView()

Step 4 − Set the delegate and load the view at the center of the screen,

UIPicker.delegate = self as UIPickerViewDelegate
UIPicker.dataSource = self as UIPickerViewDataSource
self.view.addSubview(UIPicker)
UIPicker.center = self.view.center

Step 5 − Confirm the viewController class with UIPickerViewDelegate, UIPickerViewDataSource

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource

Step 6 − Create an array of data which you want to display

let dataArray = ["English", "Maths", "History", "German", "Science"]

Step 7 − Implement the delegate methods,

func numberOfComponents(in pickerView: UIPickerView) -> Int {
   return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
   return dataArray.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
   let row = dataArray[row]
   return row
}

Step 8 − Run the application

Complete code

import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
   let dataArray = ["English", "Maths", "History", "German", "Science"]
   override func viewDidLoad() {
      super.viewDidLoad()
      let UIPicker: UIPickerView = UIPickerView()
      UIPicker.delegate = self as UIPickerViewDelegate
      UIPicker.dataSource = self as UIPickerViewDataSource
      self.view.addSubview(UIPicker)
      UIPicker.center = self.view.center
   }
   func numberOfComponents(in pickerView: UIPickerView) -> Int {
      return 1
   }
   func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
      return dataArray.count
   }
   func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
      let row = dataArray[row]
      return row
   }
}
raja
Published on 30-Aug-2019 15:08:47
Advertisements