您可以使用 NSDictionary 作为 UIPickerView 的数据源,但如果您有一个已包含键/值对的自定义 NSObject,那么使用这些对象的 NSArray 作为数据源会更简单。
假设自定义对象是 Planet,其属性为planetId (int) 和planetName (NSString)。创建一个名为planets的NSArray,其中的对象按照您希望它们在选择器中出现的顺序排列(它们不必按照planetId顺序排列)。
在 titleForRow 中,你会这样做:
return ((Planet *)[planets objectAtIndex:row]).planetName;
在 didSelectRow 中,获取选定的行星:
Planet *selectedPlanet = (Planet *)[planets objectAtIndex:row];
//
//
使用 NSDictionary,您必须将键值映射到选择器的行号。一种方法是将键值设置为行号并将自定义对象添加为值。
所以字典将像这样创建:
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];
在 titleForRow 中,你会这样做:
NSString *itemKey = [NSString stringWithFormat:@"%d", row];
Planet *planet = (Planet *)[items objectForKey:itemKey];
return planet.planetName;
在 didSelectRow 中,你会这样做:
NSString *itemKey = [NSString stringWithFormat:@"%d", row];
Planet *selectedPlanet = (Planet *)[items objectForKey:itemKey];