#import "ViewController.h"
#import "PREProvince.h"
@interface ViewController ()<UIPickerViewDataSource , UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UIPickerView *provinceView;
@property (weak, nonatomic) IBOutlet UILabel *provinceLabel;
@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
@property(nonatomic ,strong)NSArray *provinces;
@property(nonatomic ,strong)PREProvince * oldProvince;
@end
@implementation ViewController
//懒加载数据
-(NSArray *)provinces{
if (!_provinces) {
_provinces = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"02cities.plist" ofType:nil]];
NSMutableArray * tempArr = [NSMutableArray arrayWithCapacity:self.provinces.count];
for (NSDictionary * dict in _provinces) {
PREProvince * province = [PREProvince provinceWithDict:dict];
[tempArr addObject:province];
}
_provinces = tempArr;
}
return _provinces;
}
//UIPickView的数据源方法(返回组) (第一组为省,第二组为省对应的城市)
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 2;
}
//数据源方法 (返回行)
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
NSLog(@"返回行");
//判断哪一组,根据组返回对应的行数
if (component ==0) {
return self.provinces.count;
}else{
// 获取此时第一组选择的索引
NSInteger index =[pickerView selectedRowInComponent:0];
//创建一个模型对象来接收此时模型数组索引所对应的模型对象
PREProvince * oldPro =self.provinces[index];
// 声明一个成员属性来存储这个模型对象
self.oldProvince = oldPro;
return [self.provinces[index] cities].count;
}
}
// 代理方法 (返回对象组中的每一行的显示的字符串)
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
NSLog(@"显示");
if (component ==0) {
return [self.provinces[row] name];
}else{
// NSInteger index = [pickerView selectedRowInComponent:0];
//这里为什么不是行代码 ,是因为当我们两组同时滑动时,此时就会出现数组越界问题,导致程序奔溃,为了避免用户两组同时滑动,
// return [self.provinces[index] cities][row];
// 在这里就是用之前保存下来的模型对象,来返回对应的行的字符串,由于该方法会不只一次被调用,当滑动停止时,在下面的方法中会更新组中的数据的显示
return self.oldProvince.cities[row];
}
}
//选择对应某一组的某一行调用此方法
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
//根据判断对应的组,
if (component==0) {
//由于我们第一组是省,所以省变化后,需要将城市进行刷新,也就是刷新第二组
[self.provinceView reloadComponent:1];
self.provinceLabel.text =[self.provinces[row] name];
}
// NSInteger index = [pickerView selectedRowInComponent:0];
NSInteger indexCity = [pickerView selectedRowInComponent:1];
// 在这里我们不能通过获取第一组的索引来确定第二组的数据,这样当两组同时滑动时,也会出现数据越界问题,所以还需要通过保存的模型对象来确定显示的内容
self.cityLabel.text = self.oldProvince.cities[indexCity];
}