1.遵守协议
<UIPickerViewDataSource, UIPickerViewDelegate>
//存放省份
@property (nonatomic, strong) NSMutableArray *shengFen;
//存放城市
@property (nonatomic, strong) NSArray *city;
//存放 省份->城市 字典
@property (nonatomic, strong) NSMutableDictionary *dict;
//全局pickerView
@property (nonatomic, weak) UIPickerView *pickerView;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self loadData];
[self _initPickerView];
/**初始数据*/
//显示第一个省份
NSString *shengFen = [_shengFen objectAtIndex:index];
//用省份做Key取出城区数组,这样刚初始化完后就会显示省份对应的城区了
_city = [_dict objectForKey:shengFen];
}
//创建pickerView
- (void)_initPickerView
{
/**创建pickerView*/
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 40, 300, 300)];
[self.view addSubview:pickerView];
self.pickerView = pickerView;
/**设置代理*/
pickerView.dataSource = self;
pickerView.delegate = self;
}
//返回多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
//每列多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == 0) {
return _shengFen.count;
}else{
return _city.count;
}
}
//设置标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component == 0) {
return _shengFen[row];
}else{
return _city[row];
}
return 0;
}
//点击单元格调用
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0) {
/**取出当前选择的省份*/
NSString *seleteShengFen = [_shengFen objectAtIndex:row];
/**用省份做key取出数组赋值给city*/
_city = [_dict objectForKey:seleteShengFen];
/**刷新数据*/
[pickerView reloadComponent:1];
}
/**取得第0列和第1列当前显示的行数 从数组取得对应数据*/
NSInteger index = [pickerView selectedRowInComponent:0];
NSInteger index1 = [pickerView selectedRowInComponent:1];
self.lable.text = [NSString stringWithFormat:@"%@:%@",_shengFen[index] , _city[index1]];
}
//加载数据
- (void)loadData
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"city.plist" ofType:nil];
NSArray *arr = [NSArray arrayWithContentsOfFile:path];
_shengFen = [[NSMutableArray alloc] init];
_dict = [NSMutableDictionary dictionary];
for (NSDictionary *dict in arr) {
//城市列表
NSArray *city = dict[@"cities"];
//取出省份 存入数组
NSString *str = [dict objectForKey:@"state"];
[_shengFen addObject:str];
//取出城市存入数组
_city = [NSArray arrayWithArray:city];
[_dict setObject:city forKey:str];
}
}