城市选择功能实现

步骤一:解析 plist 文件,创建对应的模型。
+ (
instancetype )cityWithDict:(NSDictionary *)dict
{
   
return [[ self alloc] initWithDict:dict];
}
- (
instancetype )initWithDict:(NSDictionary *)dict
{
   
self = [ super init];
   
if ( self ) {
        [
self setValuesForKeysWithDictionary:dict];
    }
   
return self ;
}
步骤二:用一个数组将模型保存起来。
+ (NSArray *)cities
{
    NSArray *arrayC = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:
@"cities.plist" ofType: nil ]];
   
    NSMutableArray *arrayM = [NSMutableArray array];
   
for (NSDictionary *dict in arrayC) {
        SUNCityInfo *cityInfo = [
self cityWithDict:dict];
        [arrayM addObject:cityInfo];
    }
   
return arrayM;
}

- (NSString *)description
{
   
return [NSString stringWithFormat: @"<%@,%p>{name:%@,cities:%@}" , self . class , self , self .name, self .cities];
}

步骤三:手动代码创建 UIPickerView ,实现它的数据源和代理方法。

#pragma mark - 数据源
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
   
return 2 ;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
   
if (component == 0 ) {
       
return self .cities.count;
    }
else {
       
int index = [ self .picker selectedRowInComponent: 0 ];
       
        SUNCityInfo *cityInfo =
self .cities[index];
       
       
return cityInfo.cities.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
   
if (component == 0 ) {
        SUNCityInfo *cityInfo =
self .cities[row];
       
return cityInfo.name;
    }
else {
       
int index = [ self .picker selectedRowInComponent: 0 ];
       
        SUNCityInfo *cityInfo =
self .cities[index];
       
return cityInfo.cities[row];
    }
}

- (
void )pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
   
if (component == 0 ) {
        [pickerView reloadComponent:
1 ];
        [pickerView selectRow:
0 inComponent: 1 animated: YES ];
    }
   
// 获得选中的省份名称
   
int index = [ self .picker selectedRowInComponent: 0 ];
    SUNCityInfo *cityInfo =
self .cities[index];
   
int cIndex = [ self .picker selectedRowInComponent: 1 ];
   
self .cityLabel.text = [NSString stringWithFormat: @"%@ %@" ,cityInfo.name,cityInfo.cities[cIndex]] ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值