Dav*_*ave 9 iphone objective-c nsdictionary uipickerview xcode3.2
我是.NET程序员,也是Objective C的新手.
我正在尝试创建一个类似于.NET下拉列表的UIPickerView.用户看到文本列表并选择一个,并在代码中使用所选值(即ID).
我已经浏览了差不多半天试图解决这个问题.我可以添加一个带有字符串列表的常规PickerView,带有多个组件的选择器视图和带有依赖组件的选择器视图,这些组件似乎都没有回答我的查询.
请帮忙.
小智 13
您可以使用NSDictionary作为UIPickerView的数据源,但如果您有一个已包含键/值对的自定义NSObject,那么使用这些对象的NSArray作为数据源会更简单.
假设自定义对象是Planet,其属性为planetId(int)和planetName(NSString).创建一个名为行星的NSArray,其中的对象按照您希望它们出现在拾取器中的顺序(它们不必是以planetId顺序排列).
在titleForRow中,你会这样做:
return ((Planet *)[planets objectAtIndex:row]).planetName;
Run Code Online (Sandbox Code Playgroud)
在didSelectRow中,获取所选行星:
Planet *selectedPlanet = (Planet *)[planets objectAtIndex:row];
Run Code Online (Sandbox Code Playgroud)
//
//
使用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];
Run Code Online (Sandbox Code Playgroud)
在titleForRow中,你会这样做:
NSString *itemKey = [NSString stringWithFormat:@"%d", row];
Planet *planet = (Planet *)[items objectForKey:itemKey];
return planet.planetName;
Run Code Online (Sandbox Code Playgroud)
在didSelectRow中,你会这样做:
NSString *itemKey = [NSString stringWithFormat:@"%d", row];
Planet *selectedPlanet = (Planet *)[items objectForKey:itemKey];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7144 次 |
| 最近记录: |