UIPickerView选择视图的作用
- 显示多组数据和多个元素以供选择
- 例如选择日期、时间、日历效果等
- 地区选址等功能
相关协议
- UIPickerViewDelegate
普通协议,处理视图选取等普通事件协议功能
- UIPickerViewDataSource
数据处理协议,处理获取的数据时的代理功能
具体用法
@interface ViewController : UIViewController<UIPickerViewDelegate,UIPickerViewDataDelegate>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIPickerView *pickerView = [[UIPickerView alloc]init];
pickerView.frame = CGRectMake(10, 100, 300, 200);
//设置普通代理对象为当前的视图控制器
pickerView.delegate = self;
//设置数据代理对象为当前的视图控制器
pickerView.dataSource = self;
[self.view addSubview:pickerView];
}
//实现获取数组的协议函数
//返回值为选择视图的组数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 3;
}
//实现每组元素的个数
//每组元素有多少行
//P1:调用此协议的选择视图本身
//P2:第几组的元素个数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
if(component == 0)
return 2;
else if (component == 1)
return 3;
else if (component ==2)
return 2;
else
return 1;
}
//显示每个元素的内容
//P1:调用此协议的选择视图本身
//P2:行数
//P3:组数
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
NSString *str = [NSString stringWithFormat:@"%d行%d组",row+1,component+1];
return str;
}
//设置每行元素的高度
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
return 40;
}
//将自定义的视图显示到屏幕上,可以放图片上去!!
//根据需要选择实现此方法
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",(row+1)%7]];
UIImageView *iView = [[UIImageView alloc]initWithImage:image];
return iView;
}
网友评论