1 前言
UIPickerView(选择器)也是出镜率相当高的控件,类似与HTML中的Select,今天我们就一起来学习一下这个控件。
2 UIPickerView简介
关键代码:
.h文件:
#import <UIKit/UIKit.h>
//需要实现UIPickerViewDataSource,UIPickerViewDelegate协议
@interface ZYViewController : UIViewController<UIPickerViewDataSource,UIPickerViewDelegate>
@property(nonatomic,strong) UIPickerView *myPicker;
@end
.m文件:
@implementation ZYViewController
@synthesize myPicker;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
self.myPicker = [[UIPickerView alloc] init];
self.myPicker.dataSource = self;
self.myPicker.center = self.view.center;
self.myPicker.delegate = self;
//设置选择器的水平的阴影效果
self.myPicker.showsSelectionIndicator = YES;
[self.view addSubview:self.myPicker];
}
// returns the number of 'columns' to display.
//为选择器添加组建,如果需要多个组建,可以修改该方法体
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
NSInteger result = 0;
if([pickerView isEqual:self.myPicker]){
result = 1;
}
return result;
}
// returns the # of rows in each component..
//定义一个组件中有多少个选项,如果想为想象添加值,需要修改该方法体
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
NSInteger result = 0;
if ([pickerView isEqual:self.myPicker]) {
result = 10;
}
return result;
}
//UIPickerViewDelegate
//设置UIPickerView的每个组件的标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
NSString *result = nil;
if ([pickerView isEqual:self.myPicker]) {
result = [NSString stringWithFormat:@"Row %ld",(long)row+1];
}
return result;
}
//选择时候触发的事件
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSLog(@"result: You selected Row%ld",(long)row+1);
}
运行结果:
当选择某个选项时候控制台运行结果:
2013-04-22 15:27:21.163 UIPickerViewTest[649:c07] result: You selected Row1
2013-04-22 15:31:49.433 UIPickerViewTest[649:c07] result: You selected Row2
2013-04-22 15:31:51.327 UIPickerViewTest[649:c07] result: You selected Row4
3 结语
这次只是简单的介绍了一下,希望对大家有所帮助
Demo下载地址:http://download.csdn.net/detail/u010013695/5287082