省市联动案例
1、创建模型
-(instancetype) initWithDict: (NSDictionary *) dict{
if(self=[super init]){
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+(instancetype) provinceVoWithDict: (NSDictionary *) dict{
return [[self alloc] initWithDict:dict];
}
2、搭建界面和拖拽连线数据源和代理到控制器
3、懒加载数据
-(NSArray *)provinces{
if(_provinces==nil){
NSString *path=[[NSBundle mainBundle] pathForResource:@"cities.plist" ofType:nil];
NSArray *dictArray=[NSArray arrayWithContentsOfFile:path];
NSMutableArray *mArray=[NSMutableArray arrayWithCapacity:dictArray.count];
for(NSDictionary *dict in dictArray){
[mArray addObject:[ProvinceVO provinceVoWithDict:dict]];
}
_provinces=mArray;
}
return _provinces;
}
4、实现数据源方法
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 2;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
//第一组就是数组的长度
if(component==0){
return [self.provinces count];
}else{//第二组就是第一组选中的行对应的省份的所有市
NSInteger selRow=[self.pickerView selectedRowInComponent:0];
self.selProvinceVO=self.provinces[selRow];
return [self.selProvinceVO.cities count];
}
}
5、实现代理方法
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
//第一组就是显示的数组里的元素
if(component==0){
return [self.provinces[row] name];
}else{//第二组就是显示选中第一组的行所对应的省份对应的所有市
return self.selProvinceVO.cities[row];
}
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
//只有选择第一组的时候,第二组才会跟着联动
if(component==0){
[self.pickerView reloadComponent:1];
[self.pickerView selectRow:0 inComponent:1 animated:YES];
}
NSInteger selRow=[self.pickerView selectedRowInComponent:0];
NSInteger selRow2=[self.pickerView selectedRowInComponent:1];
//更新Label
self.provinceLabel.text=[self.provinces[selRow] name];
self.cityLabel.text=self.selProvinceVO.cities[selRow2];
}
6、默认选中第一行
- (void)viewDidLoad {
[super viewDidLoad];
//默认选中第一行
[self pickerView:self.pickerView didSelectRow:0 inComponent:0];
}
7、城市选择bug修复
要全局共用选择好了的省份
@property (nonatomic,strong) ProvinceVO *selProvinceVO;//第一组选中的第一行
8、注意
因为省市是关联的,所以代理方法didSelectRow中的城市选择是根据选中了的行数来展示
方法参数中的row是会根据省或者市滑动而变化,会造成下标越界,只能根据
NSInteger selRow2=[self.pickerView selectedRowInComponent:1];
self.cityLabel.text=self.selProvinceVO.cities[selRow2];

354

被折叠的 条评论
为什么被折叠?



