步骤一:解析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]]
;
}