代码如下:
- (void)viewDidLoad { [super viewDidLoad]; //先创建一个省份数组,存放三个省份名称,再创建三个小城市数组,每个数组分别对应省份的城市,最后创建一个大城市数组,存放三个小城市数组 _provinceArray = [[NSArray alloc]initWithObjects:@"河南",@"河北",@"安徽", nil]; NSArray *henanArray = [[NSArray alloc]initWithObjects:@"郑州",@"开封",@"洛阳",@"平顶山",@"安阳", nil]; NSArray *hebeiArray = [[NSArray alloc]initWithObjects:@"石家庄",@"保定",@"邢台",@"邯郸", nil]; NSArray *anhuiArray = [[NSArray alloc]initWithObjects:@"合肥",@"芜湖",@"淮南", nil]; //城市数组存放三个小城市数组,数组嵌套 _cityArray = [[NSArray alloc]initWithObjects:henanArray,hebeiArray,anhuiArray, nil]; _pickerView.dataSource = self; _pickerView.delegate = self; } //设置区数 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 2; } //设置区的行数 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { if (component == 0) { //省份区 return _provinceArray.count; } else { //城市区 //selectedRowInComponent获得某个区当前被选中的行号 NSInteger row = [pickerView selectedRowInComponent:0]; //根据被选中的省份,从大城市数组中获得对应这个省份的小城市数组 NSArray *array = [_cityArray objectAtIndex:row]; return array.count; } } //显示每行的标题 - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { if (component == 0) { //根据行号获得省份的名字 return [_provinceArray objectAtIndex:row]; } else { //首先根据被选中的省份行号获得这个省对应的城市数组 NSInteger selectedRow = [pickerView selectedRowInComponent:0]; NSArray *array = [_cityArray objectAtIndex:selectedRow]; //然后根据城市需要实现的行号从城市数组中获得对应这一行的城市名字 return [array objectAtIndex:row]; } } //方法回调 - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { if (component == 0) { //当左侧省份切换时,刷新右侧城市区 切记要刷新!!!否则程序崩溃!!! [pickerView reloadComponent:1]; } else { NSInteger selectedRow = [pickerView selectedRowInComponent:0]; NSArray *array = [_cityArray objectAtIndex:selectedRow]; _cityLabel.text = [array objectAtIndex:row]; } }效果如下: