城市選擇功能實現,城市功能實現
步驟一:解析plist檔案,建立對應的模型。
+ (instancetype)cityWithDict:(NSDictionary *)dict
{
return [[selfalloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [superinit];
if (self) {
[selfsetValuesForKeysWithDictionary:dict];
}
return self;
}
步驟二:用一個數組將模型儲存起來。
+ (NSArray *)cities
{
NSArray *arrayC = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cities.plist"ofType:nil]];
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dictin arrayC) {
SUNCityInfo *cityInfo = [selfcityWithDict: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:0inComponent:1animated: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]] ;
}