Noob enquiry regarding UIPickerView - iphone

Right guys, I am fairly new to xcode and the iPhone SDK, but have kept on it over the last few weeks, getting there slowly, however I have just started building an app which uses the UIPickerView, so far I have a picker with 7 values. When a value is selected it is displayed within a label...Pretty simple stuff. But so far I cannot find any tutorials which cover how to load a standard UIImageView to which I can then exchange images depending on what is selected within the picker.(Mug shots of each person) Do you guys now anywhere I could find some help on this or point me in the right direction.....
So far my code is pretty standard:
in the .h file I have:-
#import <UIKit/UIKit.h>
#interface Team : UIViewController
{
IBOutlet UIPickerView *pickerView;
NSMutableArray *list;
IBOutlet UILabel *pickerLabel;
IBOutlet UIImage *pickerImage;
}
#end
and in the .m file I have:-
#import "Team.h"
#implementation Team
-(NSInteger) numberOfComponentsInPickerView:(UIPickerView *)thePickerView{
return 1;
}
-(NSInteger) pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component{
return [list count];
}
-(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [list objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSString *string = [NSString stringWithFormat:#"You Selected %#", [list objectAtIndex:row]];
pickerLabel.text = string;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
list = [[NSMutableArray alloc]init];
[list addObject:#"Doug Filder"];
[list addObject:#"Chris Savage"];
[list addObject:#"Nick Bennett"];
[list addObject:#"Aimee Vacher"];
[list addObject:#"Brandy Cardwell"];
[list addObject:#"Jon West"];
[list addObject:#"Dan Parsons"];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end

You can either use an NSDictionary to store the name of the person and associate a file name,
for example:
First of all, change that UIImage to an UIImageView:
#interface Team : UIViewController
{
IBOutlet UIPickerView *pickerView;
NSMutableArray *list;
NSMutableDictionary *filenames;
IBOutlet UILabel *pickerLabel;
IBOutlet UIImageView *pickerImage;
}
#end
Then, here's how you load an image into it:
- (void)viewDidLoad {
list = [[NSMutableArray alloc]init];
[list addObject:#"Doug Filder"];
[list addObject:#"Chris Savage"];
[list addObject:#"Nick Bennett"];
[list addObject:#"Aimee Vacher"];
[list addObject:#"Brandy Cardwell"];
[list addObject:#"Jon West"];
[list addObject:#"Dan Parsons"];
filenames = [[NSMutableDictionary alloc] init];
[filenames setObject:#"DougFilder.jpg" forKey:#"Doug Filder"];
[filenames setObject:#"ChrisSavage.jpg" forKey:#"Chris Savage"];
[filenames setObject:#"NickBennett.jpg" forKey:#"Nick Bennett"];
[filenames setObject:#"AimeeVacher.jpg" forKey:#"Aimee Vacher"];
[filenames setObject:#"BrandyCardwell.jpg" forKey:#"Brandy Cardwell"];
[filenames setObject:#"JonWest.jpg" forKey:#"Jon West"];
[filenames setObject:#"DanParsons.jpg" forKey:#"Dan Parsons"];
}
-(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [list objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSString *string = [NSString stringWithFormat:#"You Selected %#", [list objectAtIndex:row]];
pickerLabel.text = string;
NSString *filename = [filenames objectForKey:[list objectAtIndex:row]];
[pickerImage setImage:[UIImage imageNamed:filename]];
}
Hope this helps! :)

just replace this
-(void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSString *string = [NSString stringWithFormat:#"You Selected %#", [list objectAtIndex:row]];
pickerLabel.text = string;
pickerImage = [UIImage imageNamed:string];
}

Related

Implement MWFeedParser in a ViewController

I'm trying to use the MWFeedParser library in my app. On my homescreen, I have a view controller named NewsViewController.
In the MWFeedParser library, the root view controller is called RootViewController. I've tried to copy all the code from the RootViewController into the NewsViewController .H + .M and in IB I've linked the tableview to "dataSource" and "delegate". But when my app starts the tableview is empty.
Here's how to code looks like:
.H:
#import <UIKit/UIKit.h>
#import "MWFeedItem.h"
#import "MWFeedParser.h"
#interface NewsViewController : UITableViewController <MWFeedParserDelegate, UITableViewDelegate, UITableViewDataSource> {
// Parsing
MWFeedParser *feedParser;
NSMutableArray *parsedItems;
// Displaying
NSArray *itemsToDisplay;
NSDateFormatter *formatter;
IBOutlet UITableView *tableView;
}
// Properties
#property (nonatomic, retain) NSArray *itemsToDisplay;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
-(IBAction)goHome;
#end
.M:
#import "NSString+HTML.h"
#import "MWFeedParser.h"
#import "DetailTableViewController.h"
#implementation NewsViewController
#synthesize itemsToDisplay, tableView;
#pragma mark -
#pragma mark View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"News", #"News");
self.tabBarItem.image = [UIImage imageNamed:#"icon_news"]; }
return self;
}
- (void)viewDidLoad
{
label.shadowOffset = CGSizeMake(0.0f, 1.0f);
label.textColor = [UIColor colorWithRed:0xB3/249.0 green:0xB3/252.0 blue:0xB3/253.0 alpha:1];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// Date
// Setup
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
parsedItems = [[NSMutableArray alloc] init];
self.itemsToDisplay = [NSArray array];
// Refresh button
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refresh)];
// Parse
NSURL *feedURL = [NSURL URLWithString:#"http://www.mywebsite.com/feed/"];
feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
feedParser.delegate = self;
feedParser.feedParseType = ParseTypeFull; // Parse feed info and all items
feedParser.connectionType = ConnectionTypeAsynchronously;
[feedParser parse];
UIImage *someImage = [UIImage imageNamed:#"back_active1#2x.png"];
[button setBackgroundImage:someImage forState:UIControlStateHighlighted];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated {
static BOOL first = YES;
if (first) {
UIViewController *popup = [[Home1ViewController alloc] initWithNibName:#"Home1ViewController" bundle:nil];
[self presentViewController:popup animated:NO completion:nil];
first = NO;
}
}
#pragma mark -
#pragma mark Parsing
// Reset and reparse
- (void)refresh {
self.title = #"Refreshing...";
[parsedItems removeAllObjects];
[feedParser stopParsing];
[feedParser parse];
self.tableView.userInteractionEnabled = NO;
self.tableView.alpha = 0.3;
}
- (void)updateTableWithParsedItems {
self.itemsToDisplay = [parsedItems sortedArrayUsingDescriptors:
[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:#"date"
ascending:NO]]];
self.tableView.userInteractionEnabled = YES;
self.tableView.alpha = 1;
[self.tableView reloadData];
}
#pragma mark -
#pragma mark MWFeedParserDelegate
- (void)feedParserDidStart:(MWFeedParser *)parser {
NSLog(#"Started Parsing: %#", parser.url);
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedInfo:(MWFeedInfo *)info {
NSLog(#"Parsed Feed Info: “%#”", info.title);
self.title = info.title;
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item {
NSLog(#"Parsed Feed Item: “%#”", item.title);
if (item) [parsedItems addObject:item];
}
- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSLog(#"Finished Parsing%#", (parser.stopped ? #" (Stopped)" : #""));
[self updateTableWithParsedItems];
}
- (void)feedParser:(MWFeedParser *)parser didFailWithError:(NSError *)error {
NSLog(#"Finished Parsing With Error: %#", error);
if (parsedItems.count == 0) {
self.title = #"Failed"; // Show failed message in title
} else {
// Failed but some items parsed, so show and inform of error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Parsing Incomplete"
message:#"There was an error during the parsing of this feed. Not all of the feed items could parsed."
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}
[self updateTableWithParsedItems];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return itemsToDisplay.count;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell.
MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
if (item) {
// Process
NSString *itemTitle = item.title ? [item.title stringByConvertingHTMLToPlainText] : #"[No Title]";
NSString *itemSummary = item.summary ? [item.summary stringByConvertingHTMLToPlainText] : #"[No Summary]";
// Set
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
cell.textLabel.text = itemTitle;
NSMutableString *subtitle = [NSMutableString string];
if (item.date) [subtitle appendFormat:#"%#: ", [formatter stringFromDate:item.date]];
[subtitle appendString:itemSummary];
cell.detailTextLabel.text = subtitle;
}
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Show detail
DetailTableViewController *detail = [[DetailTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
detail.item = (MWFeedItem *)[itemsToDisplay objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detail animated:YES];
// Deselect
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
what you do is in feedparserDidFinish method , try to reload table....like below...
- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSLog(#"Finished Parsing%#", (parser.stopped ? #" (Stopped)" : #""));
[self.tableView reloadData];
}
let me know it is working or not!!!!!
Happy Coding!!!!!!!

Error when implementing MWFeedParser

I trying to use the MWFeedParser library. I think the problem is that I want to use a view controller with a table view to display the news. Now there comes nothing up in my table view when launching the app. The code for the news view controller looks like this:
.H:
#import "MWFeedItem.h"
#import "MWFeedParser.h"
#interface NewsViewController : UIViewController <MWFeedParserDelegate> {
IBOutlet UILabel *label;
// Parsing
MWFeedParser *feedParser;
NSMutableArray *parsedItems;
// Displaying
NSArray *itemsToDisplay;
NSDateFormatter *formatter;
IBOutlet UITableView *tableView;
}
// Properties
#property (nonatomic, retain) NSArray *itemsToDisplay;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#end
.M:
#import "NSString+HTML.h"
#import "MWFeedParser.h"
#import "DetailTableViewController.h"
#implementation NewsViewController
#synthesize itemsToDisplay, tableView;
#pragma mark -
#pragma mark View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"News", #"News");
self.tabBarItem.image = [UIImage imageNamed:#"icon_news"]; }
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// Date
// Setup
self.title = #"News";
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
parsedItems = [[NSMutableArray alloc] init];
self.itemsToDisplay = [NSArray array];
// Refresh button
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refresh)];
// Parse
NSURL *feedURL = [NSURL URLWithString:#"http://www.website.com/feed/"];
feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
feedParser.delegate = self;
feedParser.feedParseType = ParseTypeFull; // Parse feed info and all items
feedParser.connectionType = ConnectionTypeAsynchronously;
[feedParser parse];
UIImage *someImage = [UIImage imageNamed:#"back_active1#2x.png"];
[button setBackgroundImage:someImage forState:UIControlStateHighlighted];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated {
static BOOL first = YES;
if (first) {
UIViewController *popup = [[Home1ViewController alloc] initWithNibName:#"Home1ViewController" bundle:nil];
[self presentViewController:popup animated:NO completion:nil];
first = NO;
}
}
#pragma mark -
#pragma mark Parsing
// Reset and reparse
- (void)refresh {
self.title = #"Refreshing...";
[parsedItems removeAllObjects];
[feedParser stopParsing];
[feedParser parse];
/*
self.tableView.userInteractionEnabled = NO;
self.tableView.alpha = 0.3;
*/
}
- (void)updateTableWithParsedItems {
self.itemsToDisplay = [parsedItems sortedArrayUsingDescriptors:
[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:#"date"
ascending:NO]]];
/* self.tableView.userInteractionEnabled = YES;
self.tableView.alpha = 1;
[self.tableView reloadData];
*/
}
#pragma mark -
#pragma mark MWFeedParserDelegate
- (void)feedParserDidStart:(MWFeedParser *)parser {
NSLog(#"Started Parsing: %#", parser.url);
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedInfo:(MWFeedInfo *)info {
NSLog(#"Parsed Feed Info: “%#”", info.title);
self.title = info.title;
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item {
NSLog(#"Parsed Feed Item: “%#”", item.title);
if (item) [parsedItems addObject:item];
}
- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSLog(#"Finished Parsing%#", (parser.stopped ? #" (Stopped)" : #""));
[self updateTableWithParsedItems];
}
- (void)feedParser:(MWFeedParser *)parser didFailWithError:(NSError *)error {
NSLog(#"Finished Parsing With Error: %#", error);
if (parsedItems.count == 0) {
self.title = #"Failed"; // Show failed message in title
} else {
// Failed but some items parsed, so show and inform of error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Parsing Incomplete"
message:#"There was an error during the parsing of this feed. Not all of the feed items could parsed."
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}
[self updateTableWithParsedItems];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return itemsToDisplay.count;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell.
MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
if (item) {
// Process
NSString *itemTitle = item.title ? [item.title stringByConvertingHTMLToPlainText] : #"[No Title]";
NSString *itemSummary = item.summary ? [item.summary stringByConvertingHTMLToPlainText] : #"[No Summary]";
// Set
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
cell.textLabel.text = itemTitle;
NSMutableString *subtitle = [NSMutableString string];
if (item.date) [subtitle appendFormat:#"%#: ", [formatter stringFromDate:item.date]];
[subtitle appendString:itemSummary];
cell.detailTextLabel.text = subtitle;
}
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Show detail
DetailTableViewController *detail = [[DetailTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
detail.item = (MWFeedItem *)[itemsToDisplay objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detail animated:YES];
// Deselect
[self->tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
In IB, I've dragged a table view onto the view and linked it to dataSource and delegate. But nothing shows up in the table view.
Would really appreciate some answers/ideas!
Thanks.
i think you should uncomment the following line in your "updateTableWithParsedItems" method:
[self.tableView reloadData];

How to pull the data from plist to UIPickerView?

can please help to provide the tutorial on how to pull the data from plist to UIPickerView?

			
				
it useful for u.
pickerViewcontroller.h
#import <UIKit/UIKit.h>
#define kStateComponent 0
#define kZipComponent 1
#interface PickerViewController : UIViewController
<UIPickerViewDataSource,UIPickerViewDelegate>{
IBOutlet UIPickerView *dpicker;
NSDictionary *stateZip;
NSArray *states;
NSArray *zips;
}
#property (nonatomic,retain) UIPickerView *dpicker;
#property (nonatomic,retain) NSDictionary *stateZip;
#property (nonatomic, retain) NSArray *states;
#property (nonatomic, retain) NSArray *zips;
#end
pickerViewcontroller.m
#import "PickerViewController.h"
#implementation PickerViewController
#synthesize dpicker;
#synthesize stateZip;
#synthesize states;
#synthesize zips;
-(void) viewDidLoad{
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath =[bundle pathForResource:#"plistfilename" ofType:#"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.stateZip=dictionary;
[dictionary release];
NSArray *component = [self.stateZip allKeys];
NSArray *sorted =[component sortedArrayUsingSelector:#selector(compare:)];
self.states=sorted;
NSString *selectedState = [self.states objectAtIndex:0];
NSArray *array = [stateZip objectForKey:selectedState];
self.zips = array;
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[dpicker release];
[stateZip release];
[states release];
[zips release];
[super dealloc];
}
#pragma mark-
#pragma mark picker Data Source Methods
-(NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerview
{
return 2;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == kStateComponent)
return [self.states count];
return [self.zips count];
}
#pragma mark picker delegate Methods
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
if(component == kStateComponent)
return[self.states objectAtIndex:row];
return [self.zips objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if(component == kStateComponent)
{
NSString *selectedState = [self.states objectAtIndex:row];
NSArray *array=[stateZip objectForKey:selectedState];
self.zips=array;
[dpicker selectRow:0 inComponent:kZipComponent animated:YES];
[dpicker reloadComponent:kZipComponent];
}
}
#end
You can create your plist like this with CNSivakumr's code!
[plistfilename.plist][1]
[1]: http://i.stack.imgur.com/zVrSe.png/Users/satishmishra/Desktop/Screen Shot 2013-04-03 at 12.27.24 PM.png

How to have two UIPickerViews together in one ViewController?

I'm trying to put 2 UIPickerViews together in one ViewController. Each UIPickerView has different data arrays. I'm using interface builder to link the pickers up. I know I'll have to use separate delegates and dataSources but I can't seem to hook everything up with interface builder correctly. Here's all my code:
pickerTesting.h
#import <UIKit/UIKit.h>
#import "picker2DataSource.h"
#interface pickerTestingViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>{
IBOutlet UIPickerView *picker;
IBOutlet UIPickerView *picker2;
NSMutableArray *pickerViewArray;
}
#property (nonatomic, retain) IBOutlet UIPickerView *picker;
#property (nonatomic, retain) IBOutlet UIPickerView *picker2;
#property (nonatomic, retain) NSMutableArray *pickerViewArray;
#end
pickerTesting.m
#import "pickerTestingViewController.h"
#implementation pickerTestingViewController
#synthesize picker, picker2, pickerViewArray;
- (void)viewDidLoad
{
[super viewDidLoad];
pickerViewArray = [[NSMutableArray alloc] init];
[pickerViewArray addObject:#" 100 "];
[pickerViewArray addObject:#" 200 "];
[pickerViewArray addObject:#" 400 "];
[pickerViewArray addObject:#" 600 "];
[pickerViewArray addObject:#" 1000 "];
[picker selectRow:1 inComponent:0 animated:NO];
picker2.delegate = self;
picker2.dataSource = self;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)picker;
{
return 1;
}
- (void)pickerView:(UIPickerView *)picker didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
}
- (NSInteger)pickerView:(UIPickerView *)picker numberOfRowsInComponent:(NSInteger)component;
{
return [pickerViewArray count];
}
- (NSString *)pickerView:(UIPickerView *)picker titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
return [pickerViewArray objectAtIndex:row];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload
{
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
And I have a separate class for the other datasource.
picker2DataSource.h
#interface picker2DataSource : NSObject <UIPickerViewDataSource, UIPickerViewDelegate>
{
NSMutableArray *customPickerArray;
}
#property (nonatomic, retain) NSMutableArray *customPickerArray;
#end
picker2DataSource.m
#import "picker2DataSource.h"
#implementation picker2DataSource
#synthesize customPickerArray;
- (id)init
{
// use predetermined frame size
self = [super init];
if (self)
{
customPickerArray = [[NSMutableArray alloc] init];
[customPickerArray addObject:#" a "];
[customPickerArray addObject:#" b "];
[customPickerArray addObject:#" c "];
[customPickerArray addObject:#" d "];
[customPickerArray addObject:#" e "];
}
return self;
}
- (void)dealloc
{
[customPickerArray release];
[super dealloc];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)picker2;
{
return 1;
}
- (void)pickerView:(UIPickerView *)picker2 didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
}
- (NSInteger)pickerView:(UIPickerView *)picker2 numberOfRowsInComponent:(NSInteger)component;
{
return [customPickerArray count];
}
- (NSString *)pickerView:(UIPickerView *)picker2 titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
return [customPickerArray objectAtIndex:row];
}
#end
Any help or code examples would be great. Thanks.
Using Interface Builder, set the tag properties of the two UIPickerViews to 1 and 2, respectively. Then, in each delegate method, use if statements to check the tag of the UIPickerView argument.
How about UIPickerViewDataSource method
//This returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 2;
}

UIPicker and send selected row data to UIView

I have written a UIPicker which is populated from a .plist. This part works fine.
What I don't know how do is once the row has been selected is to display that underlying data in another UIView.
The code in my .m file is:
#import "airlinePickerViewController.h"
#implementation airlinePickerViewController
#synthesize picker;
#synthesize airlines;
#synthesize airline;
#synthesize teleno;
- (IBAction)butonPressed:(id)sender
{
NSInteger airRow = [picker selectedRowInComponent:kAirlineComponent];
NSInteger telRow = [picker selectedRowInComponent:kTelenoComponent];
NSString *air = [self.airline objectAtIndex:airRow];
NSString *tel = [self.teleno objectAtIndex:telRow];
NSString *title = [[NSString alloc] initWithFormat:#"You selected %#.", tel];
NSString *message = [[NSString alloc] initWithFormat:#"%# is in %#", tel, air];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
[title release];
[message release];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Initialization code
}
return self;
}
- (void)viewDidLoad {
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:#"airlinedictionary" ofType:#"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.airlines = dictionary;
[dictionary release];
NSArray *components = [self.airlines allKeys];
NSArray *sorted = [components sortedArrayUsingSelector:#selector(compare:)];
self.airline = sorted;
NSString *selectedAirline = [self.airline objectAtIndex:0];
NSArray *array = [airlines objectForKey:selectedAirline];
self.teleno = array;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[picker release];
[airlines release];
[airline release];
[teleno release];
[super dealloc];
}
#pragma mark -
#pragma mark Picker Data Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == kAirlineComponent)
return [self.airline count];
return [self.teleno count];
}
#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component == kAirlineComponent)
return [self.airline objectAtIndex:row];
return [self.teleno objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == kAirlineComponent)
{
NSString *selectedAirline = [self.airline objectAtIndex:row];
NSArray *array = [airlines objectForKey:selectedAirline];
self.teleno = array;
[picker selectRow:0 inComponent:kTelenoComponent animated:YES];
[picker reloadComponent:kTelenoComponent];
}
}
#end
Can anyone help me get to grips with how to complete this task.
Many thanks
Dereck
Now a somehow general answer:
I assume you want to switch to a completely new View (not a subview) so the first thing you probably need is a Navigation Controller or TabBarController to facilitate pushing / switching to new Views. Before switching / pushing the new View you could assign the selected values as properties to that new View after initialization but before switching to the new View.