UIPickerView控件

news/2024/7/4 10:44:07

UIPickerView控件是比UIDatePicker控件更普通的Picker控件,UIDatePicker控件可以理解成是从UIPickerView控件加工出来的专门进行日期选择的控件。

UIPickerView控件的用法比UIDatePicker复杂一点。本文中的小例子将用UIPickerView控件做出两种效果,第一个只有一个转盘,第二个有两个转盘,但这两个转盘之间没有依赖关系,也就是说改变其中一个转盘中的选择,不会对第二个转盘产生影响。在下一篇文章会做一个转盘之间有依赖关系的例子。

下图是我们的效果图:

 

第一个UIPickerView控件可以用来选择Horse,Sheep,Pig,Dog,Cat,Chicken,Duck,Goose;第二个UIPickerView在第一个基础上增加了一个转盘。

闲话少说,接下来就开始。

1、运行Xcode 4.2,新建一个Single View Application,名称为UIPickerView Test1,其他设置如下图:

2、单击ViewController.xib,然后拖一个Picker View控件到视图上:

然后再拖一个Button到Picker View下方,并修改名称为Select:

3、在ViewController.h中为Picker View控件创建Outlet映射,名称为myPickerView,然后为Select按钮创建Action映射,名称为buttonPressed,具体方法不说了,可以参照上一篇文章。

4、选中Picker View控件,打开Connections Inspector,找到delegate和datasource,从它们右边的圆圈拉线到File’s Owner:

5、单击ViewController.h,在其中添加代码:

view source
print ?
01#import <UIKit/UIKit.h>
02  
03@interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>
04  
05@property (weak, nonatomic) IBOutlet UIPickerView *myPickerView;
06@property (strong, nonatomic) NSArray *myPickerData;
07  
08- (IBAction)buttonPressed:(id)sender;
09  
10@end

 注意在@interface后面添加尖括号及其中内容,我们将ViewController作为Picker View的Delegate以及DataSource。

6、代码添加:

6.1 单击ViewController.m,在@implementation的下一行添加代码:

view source
print ?
1@synthesize myPickerData;

6.2 找到buttonPressed方法,添加代码如下:

view source
print ?
01- (IBAction)buttonPressed:(id)sender {
02    NSInteger row = [myPickerView selectedRowInComponent:0]; 
03    NSString *selected = [myPickerData objectAtIndex:row]; 
04    NSString *msg = [[NSString alloc] initWithFormat: 
05                       @"You selected %@!", selected]; 
06    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello!" 
07                                                    message:msg 
08                                                   delegate:nil 
09                                          cancelButtonTitle:@"Yes, I Did." 
10                                          otherButtonTitles:nil]; 
11    [alert show]; 
12}

6.3 找到viewDidLoad方法,在其中添加代码:

view source
print ?
1- (void)viewDidLoad
2{
3    [super viewDidLoad];
4    // Do any additional setup after loading the view, typically from a nib.
5    NSArray *array = [[NSArray alloc] initWithObjects:@"Horse", @"Sheep", @"Pig", @"Dog", @"Cat", @"Chicken", @"Duck", @"Goose", nil]; 
6    self.myPickerData = array; 
7}

6.4 找到viewDidUnload方法,在其中添加代码:

view source
print ?
1- (void)viewDidUnload
2{
3    [self setMyPickerView:nil];
4    [super viewDidUnload];
5    // Release any retained subviews of the main view.
6    // e.g. self.myOutlet = nil;
7    self.myPickerView = nil;
8    self.myPickerData = nil;
9}

6.5 在@end前面添加代码:

view source
print ?
01#pragma mark - 
02#pragma mark Picker Data Source Methods 
03  
04- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { 
05    return 1; 
06
07  
08- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { 
09    return [myPickerData count]; 
10
11  
12#pragma mark Picker Delegate Methods 
13- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row             forComponent:(NSInteger)component { 
14    return [myPickerData objectAtIndex:row]; 
15}

7、运行:

 

上面的例子只有一个转盘,接下来我们在此基础上增加一个转盘,第一个转盘不变,第二个转盘可以选择Tree,Flower,Grass,Fence,House,Table,Chair,Book,Swing。只要添加代码就行了。

8、单击ViewController.h,在@interface下一行添加代码:

view source
print ?
1@property (strong, nonatomic) NSArray *myPickerData_2;

9、单击ViewController.m,在其中添加代码:

9.1 在@implementation的下一行添加代码:

view source
print ?
1@synthesize myPickerData_2;

9.2 找到viewDidLoad方法,在其中添加代码:

view source
print ?
1- (void)viewDidLoad
2{
3    [super viewDidLoad];
4    // Do any additional setup after loading the view, typically from a nib.
5    NSArray *array = [[NSArray alloc] initWithObjects:@"Horse", @"Sheep", @"Pig", @"Dog", @"Cat", @"Chicken", @"Duck", @"Goose", nil]; 
6    self.myPickerData = array;
7    NSArray *array_2 = [[NSArray alloc] initWithObjects:@"Tree", @"Flower", @"Grass", @"Fence", @"House", @"Table", @"Chair", @"Book",@"Swing" , nil]; 
8    self.myPickerData_2 = array_2; 
9}

9.3 找到viewDidUnload方法,在其中追加代码:

view source
print ?
01- (void)viewDidUnload
02{
03    [self setMyPickerView:nil];
04    [super viewDidUnload];
05    // Release any retained subviews of the main view.
06    // e.g. self.myOutlet = nil;
07    self.myPickerView = nil;
08    self.myPickerData = nil;
09    self.myPickerData_2 = nil;
10}

9.4 找到buttonPressed方法,修改代码:

view source
print ?
01- (IBAction)buttonPressed:(id)sender {
02    NSInteger row = [myPickerView selectedRowInComponent:0]; 
03    NSInteger row_2 = [myPickerView selectedRowInComponent:1];
04      
05    NSString *selected = [myPickerData objectAtIndex:row];
06    NSString *selected_2 = [myPickerData_2 objectAtIndex:row_2];
07  
08    NSString *msg = [[NSString alloc] initWithFormat: 
09                       @"You selected %@ and %@!", selected, selected_2]; 
10    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello!" 
11                                                    message:msg 
12                                                   delegate:nil 
13                                          cancelButtonTitle:@"Yes, I Did." 
14                                          otherButtonTitles:nil]; 
15    [alert show]; 
16}

9.5 找到numberOfComponentsInPickerView方法,修改其返回值为2:

view source
print ?
1- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { 
2    return 2; 
3}

9.6 找到numberOfRowsInComponent方法,修改其中代码:

view source
print ?
1- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
2    if (component == 0) {
3        return [myPickerData count]; 
4    }
5    return [myPickerData_2 count];
6}

9.7 找到下面的方法,修改代码:

view source
print ?
1- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { 
2    if (component == 0) {
3        return [myPickerData objectAtIndex:row]; 
4    }
5    return [myPickerData_2 objectAtIndex:row];
6}

10、运行:

 

 

这次要用UIPickerView控件做出这样的效果:它有两个转盘(Component),当左边的转盘改变了选择值,右边转盘所有的选项都改变。如下图所示:

 

为了达到这样的效果,还是先要创建两个NSArray对象,每个转盘对应一个。然后创建一个NSDictionary对象。我们可以想象出数据是树形的,NSDictionary可以看成是一个有两列的表格,第一列存储的是关键字,每个关键字对应一个NSArray对象,这些NSArray数组中存储的是一系列的NSString对象。

在这个例子中,第一例存储的是一些省份,第二列存储的是省份对应的地级市。

其实实现的方法跟上篇文章中的差不多,唯一不同的是要实现:改变左边转盘的选项,右边转盘内容发生相应的变化。这个功能要用到的函数我们上次也使用到了。

这次,我们先把要用到的代码写好,然后再用Interface Builder创建控件、实现映射等。

1、运行Xcode 4.2,新建一个Single View Application,名称为UIPickerView Test2:

2、创建数据。我们用到的数据如下:

view source
print ?
01江苏省:
02南京市  无锡市  徐州市  常州市  苏州市  南通市  连云港市  淮安市  盐城市  扬州市  镇江市  泰州市  宿迁市
03浙江省:
04杭州市  宁波市  温州市  嘉兴市  湖州市  绍兴市  金华市  衢州市  舟山市  台州市  丽水市
05安徽省:
06合肥市  芜湖市  蚌埠市  淮南市  马鞍山市  淮北市  铜陵市  安庆市  黄山市  滁州市  阜阳市  宿州市  巢湖市  六安市  亳州市  池州市  宣城市
07福建省:
08福州市  厦门市  莆田市  三明市  泉州市  漳州市  南平市  龙岩市  宁德市
09江西省:
10南昌市  景德镇市  萍乡市  九江市  新余市  鹰潭市  赣州市  吉安市  宜春市  抚州市  上饶市
11山东省:
12济南市  青岛市  淄博市  枣庄市  东营市  烟台市  潍坊市  济宁市  泰安市  威海市  日照市  莱芜市  临沂市  德州市  聊城市  滨州市  菏泽市
13河南省:
14郑州市  开封市  洛阳市  平顶山市  安阳市  鹤壁市  新乡市  焦作市  濮阳市  许昌市  漯河市  三门峡市  南阳市  商丘市  信阳市  周口市  驻马店市
15广东省:
16广州市  深圳市  珠海市  汕头市  韶关市  佛山市  江门市  湛江市  茂名市  肇庆市  惠州市  梅州市  汕尾市  河源市  阳江市  清远市  东莞市  中山市  潮州市  揭阳市  云浮市
17四川省:
18成都市  自贡市  攀枝花市  泸州市  德阳市  绵阳市  广元市  遂宁市  内江市  乐山市  南充市  眉山市  宜宾市  广安市  达州市  雅安市  巴中市  资阳市

在前边的文章中曾经提到过plist文件,现在,我们就要用plist文件存储以上数据。为此,选择File — New — New File,在打开的窗口中,左边选择iOS中的Resource,右边选择Property List:

单击Next,在打开的窗口中,Save As中输入名称provinceCities,Group选择Supporting Files:

单击Create,就创建了provinceCities.plist。然后往其中添加数据,如下图所示:

3、单击ViewController.h,向其中添加代码:

view source
print ?
01#import <UIKit/UIKit.h>
02  
03#define kProvinceComponent 0
04#define kCityComponent 1
05  
06@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
07  
08@property (strong, nonatomic) IBOutlet UIPickerView *picker;
09@property (strong, nonatomic) NSDictionary *provinceCities;
10@property (strong, nonatomic) NSArray *provinces;
11@property (strong, nonatomic) NSArray *cities;
12  
13- (IBAction)buttonPressed;
14  
15@end

4、单击ViewController.m,向其中添加代码:

4.1 在@implementation下一行添加代码:

view source
print ?
1@synthesize picker;
2@synthesize provinceCities;
3@synthesize provinces;
4@synthesize cities;

4.2 在ViewDidLoad方法中添加代码:

view source
print ?
01- (void)viewDidLoad
02{
03    [super viewDidLoad];
04    // Do any additional setup after loading the view, typically from a nib.
05    NSBundle *bundle = [NSBundle mainBundle];
06    NSURL *plistURL = [bundle URLForResource:@"provinceCities" withExtension:@"plist"];
07      
08    NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];
09    self.provinceCities = dictionary;
10    NSArray *components = [self.provinceCities allKeys];
11    NSArray *sorted = [components sortedArrayUsingSelector:@selector(compare:)];
12    self.provinces = sorted;
13      
14    NSString *selectedState = [self.provinces objectAtIndex:0];
15    NSArray *array = [provinceCities objectForKey:selectedState];
16    self.cities = array;
17}

代码中

view source
print ?
1NSBundle *bundle = [NSBundle mainBundle];

用于获得当前程序的Main Bundle,这个Bundle可以看成是一个文件夹,其中的内容遵循特定的框架。Main Bundle的一种主要用途是使用程序中的资源,如图片、声音等,本例中使用的是plist文件。下面的一行

view source
print ?
1NSURL *plistURL = [bundle URLForResource:@"provinceCities" withExtension:@"plist"];

用来获取provinceCities.plist的路径,之后将这个文件中的内容都放在一个NSDictionary对象中,用的是

view source
print ?
1NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];

4.3 找到viewDidUnload方法,添加代码:

view source
print ?
01- (void)viewDidUnload
02{
03    [super viewDidUnload];
04    // Release any retained subviews of the main view.
05    // e.g. self.myOutlet = nil;
06    self.picker = nil;
07    self.provinceCities = nil;
08    self.provinces = nil;
09    self.cities = nil;
10}

4.4 在@end之前添加代码,实现buttonPressed方法:

view source
print ?
01- (IBAction)buttonPressed:(id)sender {
02    NSInteger provinceRow = [picker selectedRowInComponent:kProvinceComponent];
03    NSInteger cityRow = [picker selectedRowInComponent:kCityComponent];
04      
05    NSString *province = [self.provinces objectAtIndex:provinceRow];
06    NSString *city = [self.cities objectAtIndex:cityRow];
07      
08    NSString *title = [[NSString alloc] initWithFormat:@"你选择了%@.", city];
09    NSString *message = [[NSString alloc] initWithFormat:@"%@属于%@", city, province];
10      
11    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
12    [alert show];
13}

4.5 在@end之前添加代码:

view source
print ?
01#pragma mark -
02#pragma mark Picker Date Source Methods
03- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
04    return 2;
05}
06  
07- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
08    if (component == kProvinceComponent) {
09        return [self.provinces count];
10    }
11    return [self.cities count];
12}
13  
14#pragma mark Picker Delegate Methods
15- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
16    if (component == kProvinceComponent) {
17        return [self.provinces objectAtIndex:row];
18    }
19    return [self.cities objectAtIndex:row];
20}
21  
22- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
23    if (component == kProvinceComponent) {
24        NSString *selectedState = [self.provinces objectAtIndex:row];
25        NSArray *array = [provinceCities objectForKey:selectedState];
26        self.cities = array;
27        [picker selectRow:0 inComponent:kCityComponent animated:YES];
28        [picker reloadComponent:kCityComponent];
29    }
30}
31  
32- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
33    if (component == kCityComponent) {
34        return 150;
35    }
36    return 140;
37}

可以看到,跟上篇文章的例子相比,大部分代码是一样的,不同的是增加了pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component这个方法。这个方法中,当检测到修改的是左边转盘的值,则将self.cities中的内容替换成相应的数组,并执行[picker reloadComponent:kCityComponent];这个语句。

最后一个方法

view source
print ?
1(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component

可以用来修改每个转盘的宽度,虽然在这个例子中不必要,但是我们得知道是怎么做的。

代码部分结束,接下来是使用Interface Builder添加控件、创建映射。

5、单击ViewController.xib,往其中添加一个UIPickerView控件和一个Button,按钮的名称改为“选择”,具体方法参照前面一篇文章:

接下来要做的就是拉几条线。

6、选中新添加的UIPickerView控件,按住Control,拖到File’s Owner图标,在弹出菜单选择delegate和dataSource:

打开Assistant Editor,确保其中打开的是ViewController.h,然后从picker属性前边的小圆圈拉线到UIPickerView控件:

同样,从buttonPressed方法前边的小圆圈拉线到“选择”按钮。

7、运行:

 


http://www.niftyadmin.cn/n/3653617.html

相关文章

Oracle开放Oracle App Server与Spring Framework的集成代码

From:http://blog.interface21.com/main/2007/02/27/oracle-contributing-oracle-application-server-integration-code-to-spring-framework/在应用服务器对Spring进行集成支持的主题方面,又有了新的消息.Oracle已经开始了增加产品Oracle Application Server对Spring集成的工作…

为什么开源产业不同于沃尔玛

From: http://blog.interface21.com/main/2007/03/21/why-open-source-businesses-are-not-like-wal-mart/ 非常幸运的&#xff0c;21世纪&#xff0c;已经有些成功和出众的开源项目取得了成功&#xff0c;但是&#xff0c;有趣的是&#xff0c;我们可以往回…

SUN GlassFish拥抱Spring

From:http://blog.interface21.com/main/2007/02/16/suns-glassfish-embracing-spring/Sun最近在开始开源&#xff0c;用户也开始严肃地对待Sun的开源政策。GlassFish在开源的应用服务器中是一个迟迟来到者&#xff0c;不过好象正在开始吸引众多的关注。重要的是&#xff0c;它…

UITableViewCell - UITableView中cell的边框和背景 .

UITableView是iOS开发中最常用的元素&#xff0c;在平常用的iPhone App中大部分都用到了UITableView&#xff0c;所以你应该知道她的强大了。 需求很简单&#xff0c;就是在一个UITableView里面实现一个不一样的UITableViewCell&#xff0c;如下图里的“切换账号”按钮 正常情…

自定义UITableViewCell的accessoryView 判断哪个Button按下 .

UITableview的开发中经常要自定义Cell右侧的AccessoryView&#xff0c;把他换成带图片的按钮&#xff0c;并在用户Tap时判断出是哪个自定义按钮被按下了。 创建自定义按钮&#xff0c;并设为AccessoryView if (cell nil) { cell [[UITableView alloc] initWithStyle:UITable…

Java实现的插入法建立B+树

我所实现的B树是有关于《数据库系统实现》上的B书算法的实现。利用插入法&#xff0c;我构建出了一个以long型数据作为键值&#xff0c;以Object型数据为指针的B索引树。有关我的程序的说明&#xff1a;&#xff08;1&#xff09;元组数量的取值范围的含义是&#xff1a;本程序…

自定义UINavigationBar背景图片和颜色

首先准备导航栏背景图片&#xff0c;大小 320x44, 2x文件大小640x88&#xff0c;iOS5以后更改背景图片较简单 UINavigationBar *navBar self.navigationController.navigationBar; #define kSCNavBarImageTag 10 if ([navBar respondsToSelector:selector(setBackgroundImag…

动态装载问题的研究

1 问题背景我们都知道&#xff0c;Java平台一大亮点就在于其类装载器体系结构&#xff0c;这使得JVM可以在运行期从Java API&#xff0c;扩展路经&#xff08;java.ext.path&#xff09;&#xff0c;classpath以及用户指定的位置&#xff08;文件或网络&#xff09;中载…