01、UIPickerView-案例2

省市联动案例
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];







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值