// // ViewController.m // 02-城市选中 // // Created by panba on 16-4-12. // Copyright (c) 2016年 panba. All rights reserved. // #import "ViewController.h" #import "JCCities.h" @interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate> @property(nonatomic,strong) NSArray *cities; @property(nonatomic,strong) UIPickerView *pickerView; @end @implementation ViewController //0-viewdidload - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //1-添加一个pickerview UIPickerView *pickerView = [[UIPickerView alloc]init]; //pickerView.frame = CGRectMake(0, 80, 320, 400); pickerView.dataSource = self; pickerView.delegate = self; self.pickerView = pickerView; [self.view addSubview:pickerView]; } //1-懒加载 -(NSArray *)cities { if (_cities ==nil) { //1-找到路径 NSString *fullPath = [[NSBundle mainBundle]pathForResource:@"cities.plist" ofType:nil]; //2-加载数据 NSArray *array = [NSArray arrayWithContentsOfFile:fullPath]; NSMutableArray *model = [[NSMutableArray alloc]initWithCapacity:array.count]; for (NSDictionary *dict in array) { JCCities *city = [JCCities citiesWithDict:dict]; [model addObject:city]; } _cities = [model copy]; } return _cities; } //2-返回pickerview的行数 -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 2; } //2.1返回每一组的行数 -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { if (component == 0) { return self.cities.count; }else { //1-获得到第0列选中第是第几行 NSInteger index = [self.pickerView selectedRowInComponent:0]; //2-然后得到这一个数组中城市第数组cities JCCities *city = self.cities[index]; NSArray *cities = city.cities; //3-返回城市数组第count return cities.count; } } -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { if (component ==0) { //NSInteger index = [self.pickerView selectedRowInComponent:0]; JCCities *cities = self.cities[row]; return cities.name; }else { //1-获得第0行的被选中的行数 NSInteger index = [self.pickerView selectedRowInComponent:0]; //2-得到这一个数组中的cities数组 JCCities *city = self.cities[index]; NSArray *cities = city.cities; //3-返回这一个数组中的城市名称 NSString *citiName = cities[row]; return citiName; } } //监听pickview的选中操作 -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { if (0==component) { [self.pickerView reloadComponent:1]; //让第1列自动滚到第0行 [self.pickerView selectRow:0 inComponent:1 animated:YES]; } } @end