iOS9 UIPickerView Example and Tutorial in Swift

In this instructional exercise, we’ll walk however a fundamental execution case of the UIPickerView which is a UI component that can be utilized to settle on a choice from various decisions (like what a dropdown accomplishes for a website page).

1

Making the Xcode project

We’ll begin with making a Xcode single perspective application task to show the UIPickerView.

For the project settings, you can enter any kind of points of interest following this will simply be for demo purposes.

This is the thing that I have:

no-thumbnail

Note: Since this article is not covering size classes and auto-format, we need to ensure that our UIPickerView is all around situated in the Test system. To perform this, go to the recently made Main.Storyboard document and change the wAny|hAny to wCompact|hAny to chip away at an iPhone.

Including and Joining the UIPickerView

From the file navigator on the left, select Main.Storyboard and the editorial manager will change to a configuration perspective where you can see what your perspective will resemble.

On the right hand side, you have your Attribute Inspector View (top half) and your Library View (base half). In the event that you don’t see this right hand sheet, click on the symbol in the upper right corner to flip the sheet.

Ensure you’ve chosen the Items library tab and sort in “pickerview”.

The rundown of components will channel down to the UIPickerView component.

3

Once you’ve discovered it, drag it onto your perspective. In case you can’t drop the component onto your perspective, you may be in zoomed out perspective. All things considered, simply double tap any white range in the storyboard to zoom back in and you’ll have the capacity to drop the UIPickerView component onto your perspective.

4

Since we have the Picker View component on the perspective in the storyboard, we’ll have to open this component to be available by means of code in the ViewController.

Click the Assistant Editor catch and ensure that the storyboard is in the left sheet and that ViewController.swift is in the privilege.

At that point hold down control and tap the UIPickerView component in the storyboard and drag your mouse over to the right side. Drop it in the middle of the class ViewController and override func viewDidLoad.

no-thumbnail

A little dialog will appear to approach you for a name for this IBOutlet property. Simply name it “picker”.

no-thumbnail

Subsequent to doing that, your ViewController.swift document will resemble this:

7

Presently we can reference that Picker View component from code in the ViewController utilizing “self.picker”.

Remember that in the event that you erase this IBOutlet property, you additionally need to break the association from the storyboard or else your application will crash.
You can break the association by right-tapping the Picker View component from the storyboard and searching for the association with the erased property and simply tapping the “x” beside that association.

Run your application now to ensure it doesn’t crash.

Making the Information

How about we make the information that we’re going presentation in the Picker control.

In ViewController.swift, include the accompanying code.

class ViewController: UIViewController {
    
    @IBOutlet weak var picker: UIPickerView!
    
    var pickerData: [String] = [String]()
 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        // Input data into the Array:
        pickerData = [“Item 1”, “Item 2”, “Item 3”, “Item 4”, “Item 5”, “Item 6”]
    }

 

In Line 5, we’re proclaiming another Exhibit occasion variable to store the rundown of information. By pronouncing it here as an occasion variable, we can get to this variable from any technique in this class and the variable will hold its worth for the length of time of the items lifetime.

Since the pickerData was introduced, we will include some information in Line 12, which is a piece of the viewDidLoad system.

 

Joining the Information

Since we have the UIPickerView component in our storyboard and made it open from code, we can add the code to join the information to it!

Go to ViewController.swift and make this class adjust to the UIPickerViewDelegate and UIPickerViewDataSource conventions.

Line 3 underneath is the thing that you need to adjust. By doing this, we’re stating that the ViewController class fits in with the fitting “tenets” which permits it to be an information hotspot for the UIPickerView class and permits it to handle occasions raised by the UIPickerView class. Likewise, this code really sets this ViewController example as the agent (line 14) and datasource (line 15) of the Picker View we added to the storyboard.

import UIKit
 
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    
    @IBOutlet weak var picker: UIPickerView!
    
    var pickerData: [String] = [String]()
 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        // Connect data:
        self.picker.delegate = self
        self.picker.dataSource = self
        
        // Input data into the Array:
        pickerData = [“Item 1”, “Item 2”, “Item 3”, “Item 4”, “Item 5”, “Item 6”]
    }

Presently we can execute the proper UIPickerView delegate techniques.

Add the accompanying routines to your ViewController.swift after the “didReceiveMemoryWarning” system.

override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    // The number of columns of data
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    // The number of rows of data
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }
    
    // The data to return for the row and component (column) that’s being passed in
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }

The numberOfComponentsInPickerView technique requests the quantity of sections in your picker component. For instance, in the event that you needed to do a picker for selecting time, you may have 3 segments; one for each of hour, minutes and seconds.

The numberOfRowsInComponent strategy requests the quantity of columns of information in your UIPickerView component so we give back the exhibit check.

The pickerView:titleForRow:forComponent: strategy requests the information for a particular line and particular segment.

With this information set, we just have one section so we’re simply considering which push its requesting and giving back the information thing that compares to that line.

8

How about we add more segments to our information!

In ViewController.swift, how about we change the line of code where we add our information. Rather than only a variety of string things, we should do a variety of exhibit things.

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    
    @IBOutlet weak var picker: UIPickerView!
    
    var pickerData: [[String]] = [[String]]()
 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        
        // Connect data:
        self.picker.delegate = self
        self.picker.dataSource = self
        
        // Input data into the Array:
        pickerData = [[“1”, “2”, “3”, “4”],
        [“a”, “b”, “c”, “d”],
        [“!”, “#”, “$”, “%”],
        [“w”, “x”, “y”, “z”]]
    }

We additionally need to change the numberOfComponentsInPickerView system:

// The number of columns of data
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 4
    }

We should change the pickerView:titleForRow:forComponent: system as well:

 // The data to return for the row and component (column) that’s being passed in
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[component][row]
    }

Recognizing UIPickerView determinations

Keeping in mind the end goal to recognize what the client has chosen with the UIPickerView, we just need to actualize one more delegate system:

// Catpure the picker view selection
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        // This method is triggered whenever the user makes a change to the picker selection.
        // The parameter named row and component represents what was selected.
    }

Conclusion

The UIPickerView is the iOS standard for selecting from various choices. As should be obvious from this basic UIPickerView sample, it can be troublesome for fledglings to comprehend on the off chance that they haven’t found out about designation yet. On the other hand, once you get the hang of utilizing delegates then it bodes well and you can exploit different UIElements which influence designation as well.

 

iOS9 UIPickerView Example and Tutorial in Swift