带有NSDictionary的UIPickerView [英] UIPickerView with NSDictionary

查看:102
本文介绍了带有NSDictionary的UIPickerView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是.NET程序员,是Objective C的新手。

I am a .NET programmer and new to Objective C.

我正在尝试创建一个类似于.NET下拉列表的UIPickerView。用户看到文本列表并选择一个,并在代码中使用所选值(即ID)。

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.

我已经浏览了近半天试图解决这个问题。我可以添加一个带有字符串列表的常规PickerView,带有多个组件的选择器视图和带有依赖组件的选择器视图,这些组件似乎都没有回答我的查询。

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.

请帮忙。

推荐答案

您可以使用NSDictionary作为UIPickerView的数据源,但是如果您有一个已包含键/值的自定义NSObject然后,使用这些对象的NSArray作为数据源会更简单。

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.

假设自定义对象是Planet,其属性为planetId(int)和planetName(NSString )。创建一个名为行星的NSArray,其中的对象按照您希望它们出现在拾取器中的顺序(它们不必是以planetId顺序排列)。

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).

在titleForRow中,你会这样做:

In titleForRow, you would do:

return ((Planet *)[planets objectAtIndex:row]).planetName;

在didSelectRow中,获取所选行星:

In didSelectRow, to get the selected planet:

Planet *selectedPlanet = (Planet *)[planets objectAtIndex:row];

//

//


使用NSDictionary ,您必须将键值映射到选择器的行号。一种方法是将键值设置为行号并将自定义对象添加为值。

//
//
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];

在titleForRow中,你会这样做:

In titleForRow, you would do:

NSString *itemKey = [NSString stringWithFormat:@"%d", row];
Planet *planet = (Planet *)[items objectForKey:itemKey];
return planet.planetName;

在didSelectRow中,你会这样做:

In didSelectRow, you would do:

NSString *itemKey = [NSString stringWithFormat:@"%d", row];
Planet *selectedPlanet = (Planet *)[items objectForKey:itemKey];

这篇关于带有NSDictionary的UIPickerView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆