Monday, April 22, 2013

Simple UIPickerView Example

Simple UIPickerView Example 

Step 1
      Create a Project in Xcode

Step 2
   

       Drag and drop  the "Picker View" in to " .xib " 




Step 3

 Click the ".h " file
 change the code like this


//  ViewController.h
//  UiPickerViewExample
//
//  Created by Apple on 4/22/13.
//  Copyright (c) 2013 Dhanushka Adrian. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIPickerViewDataSource, UIPickerViewDelegate>
{
    NSArray *itemsArray;
   
    IBOutlet UIPickerView *myFirstPickerView;
       
}

@property (nonatomic, strong) IBOutlet UIPickerView *myFirstPickerView;
@property (nonatomic, strong) NSArray *itemsArray;


@end

Step 4
right click the file owner




Step 5


Click the ".m " file
change the code like this



//
//  ViewController.m
//  UiPickerViewExample
//
//  Created by Apple on 4/22/13.
//  Copyright (c) 2013 Dhanushka Adrian. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize myFirstPickerView,itemsArray;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
    myFirstPickerView.delegate = self;
    myFirstPickerView.dataSource = self;
   
    itemsArray = [[NSArray alloc] initWithObjects:@"1st Year", @"2nd Year", @"3rd Year", @"4th Year", nil];
}


Step 6

add following methods to  " .m " file



- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1// returns the number of 'columns' to display.
}


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [itemsArray count];  // returns the number of rows in each component..
}


- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 30.0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [itemsArray objectAtIndex:row];
}

//If the user chooses from the pickerview, it calls this function;
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    //Let's print in the console what the user had chosen;
    NSLog(@"Your Selected item: %@", [itemsArray objectAtIndex:row]);
}


Step 7


Run the app


























No comments:

Post a Comment