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 (whic开发者_StackOverflow社区h 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.
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];
精彩评论