首页 > 其他 > 详细

城市选择功能实现

时间:2014-12-06 12:51:55      阅读:209      评论:0      收藏:0      [点我收藏+]
步骤一:解析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]] ;
}

城市选择功能实现

原文:http://blog.csdn.net/itcontend/article/details/41774259

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!