说明:事先已经准备好了一个NJProvince类,里面声明了2个属性name和cities,并创建和实现了快速创建类的动态方法和静态方法。直接导入即可。
0.创建一个plist文件,Root为Array,里面为字典(字典里为省份和城市)
1.加载这个plist文件
1>声明数组属性
@property(nonatomic,strong)NSArray *provinces;
2>懒加载(在实现文件最后面)
#pragma mark - 懒加载
-(NSArray *)provinces
{
if(_provinces == nil){
// 加载资源
NSArray *array = [NSArray arrayWithContetnsOfFile:[NSBundle mainBundle] pathForResource:@"cities.plist" ofType:nil]];
//将字典转换为模型
NSMutableArray *models = [NSMutableArray arrayWithCapacity:array.count];
for(NSDcitionary *dict in array){
NJProvince *province = [NJProvince provinceWithDictionary:dict];
[models addObject:province];
}
_provinces = [models copy];
}
return _provinces;
}
1.在viewDidLoad中
//1.创建pickerview
//pickerView 有默认的frame
UIPickerView = *pickerView = [UIPickerView alloc] init];
//2.设置数据源和代理为控制器(并实现相关协议)
pickerView.dataSource = self;
pickerView.delegate = self;
[self.view addSubview:pickerView];
self.pickerView = pickerView[具体添加原因看下面]
2.实现数据源方法和代理方法
#pragma mark - 数据源方法
//告诉系统有多少列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
注意:为了得到pickView,先声明一个weak属性UIPickerView,并在viewDidLoad中添加self.pickerView = pickerView;
//告诉系统有多少行
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponents:(NSInteger)component
{
if(0 == component){
//省份
return self.provinces.count;
} else { //城市
//0.获取第0列选中的行
NSInteger selectIndex = [self.pickerView selectedRowInComponent:0];
//1.根据第0列选中的行数获取对应省份(获取第一列选中行的模型)
NJProvince *province = self.provinces[selectIndex];
//2.获取对应省份的对应城市
NSArray *cities = province.cities;
//3.返回城市的个数
return cities.count;
}
}
#pragma mark - 代理方法
//告诉系统每一行显示什么内容
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponents:(NSInteger)component
{
if(0 == component){
//省份
return [self.provinces[row] name];
} else { //城市
//0.获取第0列选中的行
NSInteger selectIndex = [pickerView selectedRowInComponent:0];
//1.获取对应的省份
NJProvince *province = self.provinces[selectIndex];
//2.获取对应的城市
return province.cities[row];
}
}
根据选中的省份显示出对应的城市
//监听pickerView的选中
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//判断是否修改了第0列(省份列)
if(0 == component){
//刷新第1列对应的数据
pickerVIew reloadComponent:1];
//让第1列滚动到第0行
[pickerView selectRow:0 inComponent:1 animated:YES];
}