UIPickerView控件是比UIDatePicker控件更普通的Picker控件,UIDatePicker控件可以理解成是从UIPickerView控件加工出来的专门进行日期选择的控件。
UIPickerView控件的用法比UIDatePicker复杂一点。本文中的小例子将用UIPickerView控件做出两种效果,第一个只有一个转盘,第二个有两个转盘,但这两个转盘之间没有依赖关系,也就是说改变其中一个转盘中的选择,不会对第二个转盘产生影响。在下一篇文章会做一个转盘之间有依赖关系的例子。
下图是我们的效果图:
第一个UIPickerView控件可以用来选择Horse,Sheep,Pig,Dog,Cat,Chicken,Duck,Goose;第二个UIPickerView在第一个基础上增加了一个转盘。
闲话少说,接下来就开始。
1、运行Xcode,新建一个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,在其中添加代码:
#import
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIPickerView *myPickerView;
@property (strong, nonatomic) NSArray *myPickerData;
- (IBAction)buttonPressed:(id)sender;
@end
注意在@interface后面添加尖括号及其中内容,我们将ViewController作为Picker View的Delegate以及DataSource。
6、代码添加:
6.1 单击ViewController.m,在@implementation的下一行添加代码:
@synthesize myPickerData;
6.2 找到buttonPressed方法,添加代码如下:
- (IBAction)buttonPressed:(id)sender {
NSInteger row = [myPickerView selectedRowInComponent:0];
NSString *selected = [myPickerData objectAtIndex:row];
NSString *msg = [[NSString alloc] initWithFormat:
@"You selected %@!", selected];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello!"
message:msg
delegate:nil
cancelButtonTitle:@"Yes, I Did."
otherButtonTitles:nil];
[alert show];
}
6.3 找到viewDidLoad方法,在其中添加代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *array = [[NSArray alloc] initWithObjects:@"Horse", @"Sheep", @"Pig", @"Dog", @"Cat", @"Chicken", @"Duck", @"Goose", nil];
self.myPickerData = array;
}
6.4 找到viewDidUnload方法,在其中添加代码:
- (void)viewDidUnload
{
[self setMyPickerView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.myPickerView = nil;
self.myPickerData = nil;
}
6.5 在@end前面添加代码:
#pragma mark -
#pragma mark Picker Data Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [myPickerData count];
}
#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [myPickerData objectAtIndex:row];
}
7、运行:
上面的例子只有一个转盘,接下来我们在此基础上增加一个转盘,第一个转盘不变,第二个转盘可以选择Tree,Flower,Grass,Fence,House,Table,Chair,Book,Swing。只要添加代码就行了。
8、单击ViewController.h,在@interface下一行添加代码:
@property (strong, nonatomic) NSArray *myPickerData_2;
9、单击ViewController.m,在其中添加代码:
9.1 在@implementation的下一行添加代码:
@synthesize myPickerData_2;
9.2 找到viewDidLoad方法,在其中添加代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *array = [[NSArray alloc] initWithObjects:@"Horse", @"Sheep", @"Pig", @"Dog", @"Cat", @"Chicken", @"Duck", @"Goose", nil];
self.myPickerData = array;
NSArray *array_2 = [[NSArray alloc] initWithObjects:@"Tree", @"Flower", @"Grass", @"Fence", @"House", @"Table", @"Chair", @"Book",@"Swing" , nil];
self.myPickerData_2 = array_2;
}
9.3 找到viewDidUnload方法,在其中追加代码:
- (void)viewDidUnload
{
[self setMyPickerView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.myPickerView = nil;
self.myPickerData = nil;
self.myPickerData_2 = nil;
}
9.4 找到buttonPressed方法,修改代码:
- (IBAction)buttonPressed:(id)sender {
NSInteger row = [myPickerView selectedRowInComponent:0];
NSInteger row_2 = [myPickerView selectedRowInComponent:1];
NSString *selected = [myPickerData objectAtIndex:row];
NSString *selected_2 = [myPickerData_2 objectAtIndex:row_2];
NSString *msg = [[NSString alloc] initWithFormat:
@"You selected %@ and %@!", selected, selected_2];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello!"
message:msg
delegate:nil
cancelButtonTitle:@"Yes, I Did."
otherButtonTitles:nil];
[alert show];
}
9.5 找到numberOfComponentsInPickerView方法,修改其返回值为2:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 2;
}
9.6 找到numberOfRowsInComponent方法,修改其中代码:
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (component == 0) {
return [myPickerData count];
}
return [myPickerData_2 count];
}
9.7 找到下面的方法,修改代码:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if (component == 0) {
return [myPickerData objectAtIndex:row];
}
return [myPickerData_2 objectAtIndex:row];
}
10、运行:
进阶实例
下面要用UIPickerView控件做出这样的效果:它有两个转盘(Component),当左边的转盘改变了选择值,右边转盘所有的选项都改变。如下图所示:
为了达到这样的效果,还是先要创建两个NSArray对象,每个转盘对应一个。然后创建一个NSDictionary对象。我们可以想象出数据是树形的,NSDictionary可以看成是一个有两列的表格,第一列存储的是关键字,每个关键字对应一个NSArray对象,这些NSArray数组中存储的是一系列的NSString对象。
在这个例子中,第一例存储的是一些省份,第二列存储的是省份对应的地级市。
其实实现的方法跟上篇文章中的差不多,唯一不同的是要实现:改变左边转盘的选项,右边转盘内容发生相应的变化。这个功能要用到的函数我们上次也使用到了。
这次,我们先把要用到的代码写好,然后再用Interface Builder创建控件、实现映射等。
1、运行Xcode 4.2,新建一个Single View Application,名称为UIPickerView Test2:
2、创建数据。我们用到的数据如下:
在前边的文章中曾经提到过plist文件,现在,我们就要用plist文件存储以上数据。为此,选择File ― New ― New File,在打开的窗口中,左边选择iOS中的Resource,右边选择Property List:
单击Next,在打开的窗口中,Save As中输入名称provinceCities,Group选择Supporting Files:
单击Create,就创建了provinceCities.plist。然后往其中添加数据,如下图所示:
3、单击ViewController.h,向其中添加代码:
#import
#define kProvinceComponent 0
#define kCityComponent 1
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIPickerView *picker;
@property (strong, nonatomic) NSDictionary *provinceCities;
@property (strong, nonatomic) NSArray *provinces;
@property (strong, nonatomic) NSArray *cities;
- (IBAction)buttonPressed;
@end
4、单击ViewController.m,向其中添加代码:
4.1 在@implementation下一行添加代码:
@synthesize picker;
@synthesize provinceCities;
@synthesize provinces;
@synthesize cities;
4.2 在ViewDidLoad方法中添加代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSBundle *bundle = [NSBundle mainBundle];
NSURL *plistURL = [bundle URLForResource:@"provinceCities" withExtension:@"plist"];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];
self.provinceCities = dictionary;
NSArray *components = [self.provinceCities allKeys];
NSArray *sorted = [components sortedArrayUsingSelector:@selector(compare:)];
self.provinces = sorted;
NSString *selectedState = [self.provinces objectAtIndex:0];
NSArray *array = [provinceCities objectForKey:selectedState];
self.cities = array;
}
代码中
NSBundle *bundle = [NSBundle mainBundle];
用于获得当前程序的Main Bundle,这个Bundle可以看成是一个文件夹,其中的内容遵循特定的框架。Main Bundle的一种主要用途是使用程序中的资源,如图片、声音等,本例中使用的是plist文件。下面的一行
NSURL *plistURL = [bundle URLForResource:@"provinceCities" withExtension:@"plist"];
用来获取provinceCities.plist的路径,之后将这个文件中的内容都放在一个NSDictionary对象中,用的是
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];
4.3 找到viewDidUnload方法,添加代码:
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.picker = nil;
self.provinceCities = nil;
self.provinces = nil;
self.cities = nil;
}
4.4 在@end之前添加代码,实现buttonPressed方法:
- (IBAction)buttonPressed:(id)sender {
NSInteger provinceRow = [picker selectedRowInComponent:kProvinceComponent];
NSInteger cityRow = [picker selectedRowInComponent:kCityComponent];
NSString *province = [self.provinces objectAtIndex:provinceRow];
NSString *city = [self.cities objectAtIndex:cityRow];
NSString *title = [[NSString alloc] initWithFormat:@"你选择了%@.", city];
NSString *message = [[NSString alloc] initWithFormat:@"%@属于%@", city, province];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alert show];
}
4.5 在@end之前添加代码:
#pragma mark -
#pragma mark Picker Date Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (component == kProvinceComponent) {
return [self.provinces count];
}
return [self.cities count];
}
#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if (component == kProvinceComponent) {
return [self.provinces objectAtIndex:row];
}
return [self.cities objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if (component == kProvinceComponent) {
NSString *selectedState = [self.provinces objectAtIndex:row];
NSArray *array = [provinceCities objectForKey:selectedState];
self.cities = array;
[picker selectRow:0 inComponent:kCityComponent animated:YES];
[picker reloadComponent:kCityComponent];
}
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
if (component == kCityComponent) {
return 150;
}
return 140;
}
可以看到,跟上篇文章的例子相比,大部分代码是一样的,不同的是增加了pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component这个方法。这个方法中,当检测到修改的是左边转盘的值,则将self.cities中的内容替换成相应的数组,并执行[picker reloadComponent:kCityComponent];这个语句。
最后一个方法
(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、运行: