UIPickerView 与 NSDictionary
我是一名 .NET 程序员,对 Objective C 很陌生。
我正在尝试制作一个 UIPickerView,它的作用类似于 .NET 下拉列表。用户看到文本列表并选择一个,所选值(即 ID)将在代码中使用。
我已经浏览了近半天试图弄清楚这一点。我可以添加一个带有字符串列表的常规 PickerView、带有多个组件的选择器视图和带有依赖组件的选择器视图,但这些视图似乎都无法回答我的查询。
请帮忙。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 NSDictionary 作为 UIPickerView 的数据源,但如果您有一个已包含键/值对的自定义 NSObject,那么使用这些对象的 NSArray 作为数据源会更简单。
假设自定义对象是 Planet,其属性为planetId (int) 和planetName (NSString)。创建一个名为planets的NSArray,其中的对象按照您希望它们在选择器中出现的顺序排列(它们不必按照planetId顺序排列)。
在 titleForRow 中,您可以执行以下操作:
在 didSelectRow 中,获取选定的行星:
//
//
使用 NSDictionary,您必须将键值映射到选择器的行号。一种方法是将键值设置为行号并将自定义对象添加为值。
因此,字典将像这样创建:
在 titleForRow 中,您将执行以下操作:
在 didSelectRow 中,您将执行以下操作:
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:
In didSelectRow, to get the selected planet:
//
//
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:
In titleForRow, you would do:
In didSelectRow, you would do: