城市选择器,借助于UIPickerView来实现,第一列为省份,第二列为第一列省份对应的城市或者区,数据放在plist中,plist结构如下图所示,第一层是一个Dictionary,每个省份对应的城市是一个Array:
实现步骤
第一步
拖入一个UIPickerView到StoryBoard中,然后设置UIPickerViewDelegate,和UIPickerViewDataSource为当前的控制器,如下图红色区域所示:
第二步
在对应的ViewController中进行实现,代码注释非常详细
#import "ViewController.h"
@interface ViewController () <UIPickerViewDelegate, UIPickerViewDataSource>
/**
* plist对应的字典
*/
@property (nonatomic, strong) NSDictionary* cityNames;
/**
* 省份
*/
@property (nonatomic, strong) NSArray* provinces;
/**
* 城市
*/
@property (nonatomic, strong) NSArray* cities;
/**
* 选中的省份
*/
@property (nonatomic, strong) NSString* selectedProvince;
@end
@implementation ViewController
/**
* 懒加载plist
*
* @return plist对应的字典
*/
- (NSDictionary*)cityNames
{
if (_cityNames == nil) {
NSString* path = [[NSBundle mainBundle] pathForResource:@"cityData" ofType:@"plist"];
_cityNames = [NSDictionary dictionaryWithContentsOfFile:path];
}
return _cityNames;
}
/**
* 懒加载省份
*
* @return 省份对应的数组
*/
- (NSArray*)provinces
{
if (_provinces == nil) {
//将省份保存到数组中 但是字典保存的是无序的 所以读出来的省份也是无序的
_provinces = [self.cityNames allKeys];
}
return _provinces;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//设置默认选中的省份是provinces中的第一个元素
self.selectedProvince = self.provinces[0];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/**
* 返回每一列的行数
*
* @param pickerView
* @param component
*
* @return
*/
- (NSInteger)pickerView:(UIPickerView*)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == 0) {
return self.provinces.count;
}
else {
self.cities = [self.cityNames valueForKey:self.selectedProvince];
return self.cities.count;
}
}
/**
* 返回每一行显示的文本
*
* @param pickerView
* @param row
* @param component
*
* @return
*/
- (NSString*)pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
//第一列返回所有的省份
if (component == 0) {
return self.provinces[row];
}
else {
self.cities = [self.cityNames valueForKey:self.selectedProvince];
return self.cities[row];
}
}
/**
* 一共多少咧
*
* @param pickerView
*
* @return
*/
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
return 2;
}
/**
* 选中某一行后回调 联动的关键
*
* @param pickerView
* @param row 用户选择的省份
* @param component
*/
- (void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0) {
//选中的省份
self.selectedProvince = self.provinces[row];
//重新加载第二列的数据
[pickerView reloadComponent:1];
//让第二列归位
[pickerView selectRow:0 inComponent:1 animated:YES];
}
}
@end
实现效果
附件
plist文件下载地址:http://pan.baidu.com/s/1dETRthZ