有时候我们需呀输入的内容是联动的,比如省份与城市,书名与章节等,这时候我们可以使用UipickerVIew来实现.
首先向设计界面中拖入一个pickerView并关联代码,同时设置dataSource和delegate代理.
注:不要忘了在.h文件中添加协议
@PRoperty (weak, nonatomic) IBOutlet UIPickerView *pickerView; @property (nonatomic,retain)NSMutableArray *nameArray; @property(nonatomic,retain)NSMutableArray *contentArray;
初始化数组,获得数据,此处采用本地数据
//初始化数组 _nameArray =[[NSMutableArray alloc]initWithObjects:@"第一章",@"第二章",@"第三章",@"第四章",@"第五章",@"第六章", nil]; _contentArray=[[NSMutableArray alloc]initWithCapacity:0]; //给内容数组中添加小数组 for (int i=0; i<_nameArray.count; i++) { NSMutableArray *array =[[NSMutableArray alloc]initWithCapacity:0]; for (int j =0; j<i+5; j++) { NSString *str =[NSString stringWithFormat:@"第%d.第%d节",i+1,j+1]; [array addObject:str]; } //把存过值的小数组追加到大数组中去 [_contentArray addObject:array];
UIPickerViewDataSource协议方法
//设置区数 -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 2; } -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { //左区内容大小 if (component==0) { return _nameArray.count; } else //右区 { //拿到左半区索引,根据索引找到右半区对应数据数组,返回内容大小 long int num=[pickerView selectedRowInComponent:0]; NSMutableArray *array=_contentArray[num]; return array.count; } }
UIPickerViewDelegate协议方法
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
//当前为一区,根据行数返回相应的数据
if (component==0) {
return _nameArray[row];
}
else
{
//获取索引值,取得对应数据数组,根据行数返回数据
long int num=[pickerView selectedRowInComponent:0];
NSMutableArray *array=_contentArray[num];
NSString *titleStr=array[row];
return titleStr;
}
}
//选择某行时调用
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//只有当前是左侧区域操作的时候才允许刷新
if (component==0) {
[pickerView reloadComponent:1];
[pickerView selectRow:0 inComponent:1 animated:YES];
}
}
运行效果如图: