初始化
_pickerView = [[UIPickerViewalloc]init]; _pickerView.center =self.view.center; [self.viewaddSubview:_pickerView];
添加数据
<UIPickerViewDataSource> _pickerView.dataSource =self; //返回pickerView要显示的组件的条目 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { NSInteger result =0; if ([pickerViewisEqual:_pickerView]) { result = 1;//Figure-2.1 // result = 2;//Figure-2.2 } return result; } //返回每个组件的数据条目 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { NSInteger result =0; if ([pickerViewisEqual:_pickerView]) { result = 10; } return result; }
添加代理
<UIPickViewDelegate>
_pickerView.delegate =self;
//给每个组件的title赋值
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *title =nil;
if ([pickerViewisEqual:_pickerView]) {
title = [NSStringstringWithFormat:@"Row %ld",(long)row + 1];
}
return title;
}
显示选中指示:
_pickerView.showsSelectionIndicator = YES;
选择子项:
1.添加数据源
@interface ViewController (){
NSArray *pickerDatas;
}
pickerDatas = [NSArrayarrayWithObjects:@"Row1",@"Row2",@"Row3",@"Row4",@"Row5",@"Row6",@"Row7",nil];
2.修改pickerview的返回条目
//返回每个组件的数据条目
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
NSInteger result =0;
if ([pickerViewisEqual:_pickerView]) {
result = [pickerDatascount];
}
return result;
}
3.修改pickerview的赋值
//给每个组件的title赋值
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *title =nil;
if ([pickerViewisEqual:_pickerView]) {
title = [NSStringstringWithFormat:@"%@",pickerDatas[row]];
}
return title;
}
4.添加选中pickerview子项方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSString *title =pickerDatas[row];
UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"Picker Selected"message:titledelegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil,nil];
[alert show];
}