UIPickerView with NSDictionary

Deadly 提交于 2019-11-30 07:12:32

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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!