UIPickerView
UIPickerView
NSDictionary *dataDic= @{@"A":
@{@"one":@[@"a1",@"a2",@"a3"],@"two":@[@"b1",@"b2",@"b3"]},
@"B":@{@"three":@[@"c1",@"c2",@"c2"],@"four":@[@"c1",@"c2",@"c3"]}};
//UIPickerView:选择器
UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 30, 300, 150)];
//导入代理协议UIPickerViewDelegate:选择协议//UIPickerViewDataSources:数据源,显示列/行//设置代理
picker.delegate=self;
//设置数据源代理
picker.dataSource=self;
[self.view addSubview:picker];
//返回多少个区域(列)
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView {
return3;
}
//每个区域返回多少行
- (NSInteger)pickerView:(UIPickerView*)pickerView numberOfRowsInComponent:(NSInteger)component {
switch(component) {
case 0://A
{
return [dataDic allKeys].count;
}
break;
case1://one/two/three/four
{
//区域选择的行selectedRowInComponent:index()
NSInteger shengRow = [pickerView selectedRowInComponent:0];
//省的名字
NSString*shengName = [dataDic allKeys][shengRow];
//市的字典返回市的行数
NSDictionary *shiDic = [dataDic objectForKey:shengName];
return [shiDic allKeys].count;
}
break;
case2://区
{
//先找省
NSInteger shengRow = [pickerView selectedRowInComponent:0];
NSString*shengName = [dataDic allKeys][shengRow];
//找市
NSDictionary*shiDic = [dataDicobjectForKey:shengName];
//返回选择的市
NSInteger shiRow = [pickerView selectedRowInComponent:1];
NSString *shiName = [shiDic allKeys][shiRow];
//通过用户选择的市的名字来找到对应的区数组
//NSArray *quArray = [shiDic objectForKey:shiName];
NSArray *quArray = shiDic[shiName];
//返回区的行数
return quArray.count;
}
break;
default:
return0;
break;
}
}
//返回标题
- (NSString*)pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if(component == 0) {//省
//返回省的名字
return [dataDic allKeys][row];
}elseif(component == 1){//市
//省区域选择的行
NSInteger shengRow = [pickerView selectedRowInComponent:0];
//通过选择的省索引拿到省的名字
NSString *shengName = [dataDic allKeys][shengRow];
//市的字典返回市的行数注意接收的类型
NSDictionary *shiDic = [dataDic objectForKey:shengName];
//返回市的所有名字
return [shiDic allKeys][row];
}else{//区
//先找省
NSInteger shengRow = [pickerView selectedRowInComponent:0];
//返回选择的市
NSIntegershiRow = [pickerViewselectedRowInComponent:1];
//通过用户选择的省索引去找省名字
NSString *shengName = [dataDic allKeys][shengRow];
//通过省的名字去拿市(字典的格式)
NSDictionary *shiDic = [dataDic objectForKey:shengName];
NSString *shiName = [shiDic allKeys][shiRow];
//通过用户选择的市的名字来找到对应的区数组
NSArray *quArray = [shiDic objectForKey:shiName];
//返回区的每一行的标题
return quArray[row];
}
}
//选择的触发方法:当前选中是哪一个区域中的哪一行
- (void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if(component == 0) {
[pickerView reloadComponent:1];
[pickerView reloadComponent:2];
} elseif (component == 1){
[pickerView reloadComponent:2];
}else{
}
}