UIPickerView with NSDictionary
Asked Answered
L

1

9

I am a .NET programmer and new to Objective C.

I am trying to make a UIPickerView which acts like a .NET dropdownlist. User sees the list of text and selects one and the selected value (which is the ID) is used in code.

I have been browsing for almost half a day trying to figure this out. I could add a regular PickerView with list of strings, picker view with mulitple components and picker view with dependent components none of which seems to answer my query.

Please help.

Latty answered 9/3, 2010 at 0:59 Comment(2)
The UIPickerView is not going to look or behave exactly like the .net dropdownlist but the essential functionality is there. Aside from the appearance, is there a specific problem you're having?Abernon
i just want to use a key-value pair for data source for UIPickerView. Looks like thats not possible. I have a custom NSObject [with Name and ID properties]. I set the Names to display on the UIPickerView. When user selects a name, I need to find the ID of the Name and use it. Thanks for your reply.Latty
A
14

You can use a NSDictionary as a data source for UIPickerView but if you have a custom NSObject that already contains the key/value pair then it would be simpler to use an NSArray of those objects as the data source.

Assume the custom object is Planet with the properties planetId (int) and planetName (NSString). Create an NSArray called planets with the objects in the order you want them to appear in the picker (they don't have to be in planetId order).

In titleForRow, you would do:

return ((Planet *)[planets objectAtIndex:row]).planetName;

In didSelectRow, to get the selected planet:

Planet *selectedPlanet = (Planet *)[planets objectAtIndex:row];

//
//
With an NSDictionary, you would have to map the key values to the row number of the picker. One way to do that is to just set the key values to the row numbers and add the custom objects as the values.

So the dictionary would be created like this:

NSArray *keys = [NSArray arrayWithObjects:@"0", @"1", @"2", @"3", nil];
NSArray *values = [NSArray arrayWithObjects:mercury, venus, earth, mars, nil];
items = [[NSDictionary dictionaryWithObjects:values forKeys:keys] retain];

In titleForRow, you would do:

NSString *itemKey = [NSString stringWithFormat:@"%d", row];
Planet *planet = (Planet *)[items objectForKey:itemKey];
return planet.planetName;

In didSelectRow, you would do:

NSString *itemKey = [NSString stringWithFormat:@"%d", row];
Planet *selectedPlanet = (Planet *)[items objectForKey:itemKey];
Abernon answered 10/3, 2010 at 13:47 Comment(3)
Exactly what I was searching for, thanks @DyingCactus!Interoffice
Can i have this code in Swift.I really need it.Please HelpMeatiness
Ok.I done this.But i need dependent pickerView like this. help me out from this issue... gist.github.com/anonymous/a5f75372802fb8c28c6f @DyingCactusFlannery

© 2022 - 2024 — McMap. All rights reserved.