articles

home / developersection / articles / uipickerview controller in ios

UIPickerView Controller in iOS

Tarun Kumar 5.83 K 27-Oct-2015

In iOS app developmentUIKit frameworklibrary provides a controller known asUIPickerView, with this help we will create a currency converter. With this currency converter user can calculate currency and foreign exchange rates. I our app we provide the facility to enter value in text box and select the currency from picker view and display the equivalent amount in the label according to the chosen currency. For creating this app we need to  implementUIPickerViewDelegateandUIPickerViewDataSourcein our interface. 


UIPickerViewDelegate provides some necessary methods to design or display values into picker view perfectly and UIPickerViewDataSource is used to store the list of records to display into picker view. 


We must need to implement these methods in our app: 

       numberOfComponentsInPickerView:this method is used to identify the number of components to display.

        numberOfRowsInComponent:this method is used to inform the picker view to display the no of rows in the specified component.

       titleForRow:used to identify the strings that is to be displayed in the specific row in a specific component.

 
Steps to create app using UIPickerView Controller: 


1.     In Xcode goto File >New> click on'Project'> select'Single View Application'

and click on'Next'button > enter Product Name as'PickerViewController'and

press'Next'and after select location where you want to save the file and

click'Finish'button. 


2.     Now, selectStoryboardand add aLabel, atext field, and

aUIPickerViewcontroller from'Show Object Library'. 


3.     Now, selectViewController.hfile and

implementUIPickerViewDelegateandUIPickerViewDataSource, like this:


@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>

 4.   Now, define outlets of 'dollarText', 'resultLabel', and 'picker' and two arrays 'countyNames' and 'exchangeRates' and a method to disable the keyboard when we click on 'return' button of keyboard.

@property (strong, nonatomic) IBOutlet UITextField *dollarText;

@property (strong, nonatomic) IBOutlet UILabel *resultLabel;

@property (strong, nonatomic) IBOutlet UIPickerView *picker;

@property (strong, nonatomic) NSArray *countryNames;

@property (strong, nonatomic) NSArray *exchangeRates;

-(IBAction)textFieldReturn:(id)sender;


5.    Now, in ViewController.m file, @synthesize all the @properties in the implementation section, like this:

@implementation ViewController

@synthesize dollarText, resultLabel, picker;

@synthesize countryNames, exchangeRates;


 6. Now in viewDidLoad: method under [super viewDidLoad]; statement, add the currency names into the countynames array and currency values in the exchangeRates array. These records are used to be display in the PickerView controller and as result. After defining it looks like this:

self.countryNames = [[NSArray alloc] initWithObjects:

                         @"Indian Rupee",

                         @"Australian Dollar",

                         @"Brazilian Real",

                         @"Chinese Yuan",

                         @"France",

                         @"Great Britain",

                         @"Japanese Yen", nil];

 

            self.exchangeRates = [[NSArray alloc] initWithObjects:

                          [NSNumber numberWithFloat:64.95],

                          [NSNumber numberWithFloat:1.38],

                          [NSNumber numberWithFloat:3.91],

                          [NSNumber numberWithFloat:6.39],

                          [NSNumber numberWithFloat:0.91],

                          [NSNumber numberWithFloat:0.6206],

                          [NSNumber numberWithFloat:120.45], nil];

 7. Now, in numberOfComponentsInPickerView: method return value will be 1 because this method is responsible for no of components to be display in the view, like this:

             return 1; 

8.   Now, the second methodnumberOfRowsInComponent:returns the no of rows in the components, so we will count the no of elements in the countyNames array and return it.

            return [countryNames objectAtIndex:row]; 

9.   Now, the third methoddidSelectedRow:is called when we select any row in the pickerView method takes the row number in argument and use it as an index to obtain the exchange rate from the exchangeRates array.

10. Next, the entered amount by the user is converted from string to a floating points and after we calculate it according to the selected currency and display it in the result label.

11. Next, implement the action method to disable the keyboard after clicking return button on keyboard.

Now, our app is almost done but when we run our app it will run without any problem but when we click on pickerView controller we will get error. Because we are not coding to add any value into pickerview component.

To add value into the pickerView component, click on Storyboard and select the view controller, now right click on thepickerView, a picker dialog box will open like this:

 


 

now, click on the round circle and drag it into the File's Owner object. And repeat this task for the delegate outlet. After dragging outlets round circle displayed with white color. Like this:

that's it all the work is done, now run the app, app will look like this:

 

Now, enter 1 in the text field and select Indian Rupee from the picker view list, result is displayed in the Label; it looks like this:

 

Source code is here:

 

ViewController.h

#import <UIKit/UIKit.h>

 

@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>

{

    UITextField *dollarText;

    UILabel *resultLabel;

    UIPickerView *picker;

   

    NSArray *countryNames;

    NSArray *exchangeRates;

}

@property (strong, nonatomic) IBOutlet UITextField *dollarText;

@property (strong, nonatomic) IBOutlet UILabel *resultLabel;

@property (strong, nonatomic) IBOutlet UIPickerView *picker;

 

@property (strong, nonatomic) NSArray *countryNames;

@property (strong, nonatomic) NSArray *exchangeRates;

 

-(IBAction)textFieldReturn:(id)sender;

 

@end

 

ViewController.m

#import "ViewController.h"

 

@interface ViewController ()

@end

 

@implementation ViewController

@synthesize dollarText, resultLabel, picker;

@synthesize countryNames, exchangeRates;

 

- (void)viewDidLoad {

    [super viewDidLoad];

    self.countryNames = [[NSArray alloc] initWithObjects:

                         @"Indian Rupee",

                         @"Australian Dollar",

                         @"Brazilian Real",

                         @"Chinese Yuan",

                         @"France",

                         @"Great Britain",

                         @"Japanese Yen", nil];

   

    self.exchangeRates = [[NSArray alloc] initWithObjects:

                          [NSNumber numberWithFloat:64.95],

                          [NSNumber numberWithFloat:1.38],

                          [NSNumber numberWithFloat:3.91],

                          [NSNumber numberWithFloat:6.39],

                          [NSNumber numberWithFloat:0.91],

                          [NSNumber numberWithFloat:0.6206],

                          [NSNumber numberWithFloat:120.45], nil];

}

 

- (NSInteger)numberOfComponentsInPickerView: (UIPickerView *)pickerView

{

    return 1;

}

 

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:

(NSInteger)component

{

    return [countryNames count];

}

 

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row

forComponent:(NSInteger)component

{

    return [countryNames objectAtIndex:row];

}

 

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row

inComponent:(NSInteger)component

{

    float rate = [[exchangeRates objectAtIndex:row] floatValue];

    float dollars = [dollarText.text floatValue];

    float result = dollars * rate;

   

    NSString *resultString = [[NSString alloc] initWithFormat:

                              @"%.2f USD = %.2f %@", dollars, result,

                              [countryNames objectAtIndex:row]];

    resultLabel.text = resultString;

}

 

-(IBAction)textFieldReturn:(id)sender

{

    [sender resignFirstResponder];

}

 

- (void)viewDidUnload

{

    [super viewDidUnload];

 

    self.resultLabel = nil;

    self.dollarText = nil;

    self.picker = nil;

}

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end


Updated 07-Sep-2019

Leave Comment

Comments

Liked By