城市選擇器烦却,借助于UIPickerView來實(shí)現(xiàn),第一列為省份先巴,第二列為第一列省份對(duì)應(yīng)的城市或者區(qū)其爵,數(shù)據(jù)放在plist中,plist結(jié)構(gòu)如下圖所示伸蚯,第一層是一個(gè)Dictionary摩渺,每個(gè)省份對(duì)應(yīng)的城市是一個(gè)Array:
實(shí)現(xiàn)步驟
第一步
拖入一個(gè)UIPickerView到StoryBoard中,然后設(shè)置UIPickerViewDelegate,和UIPickerViewDataSource為當(dāng)前的控制器剂邮,如下圖紅色區(qū)域所示:
第二步
在對(duì)應(yīng)的ViewController中進(jìn)行實(shí)現(xiàn)摇幻,代碼注釋非常詳細(xì)
#import "ViewController.h"
@interface ViewController () <UIPickerViewDelegate, UIPickerViewDataSource>
/**
* plist對(duì)應(yīng)的字典
*/
@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對(duì)應(yīng)的字典
*/
- (NSDictionary*)cityNames
{
if (_cityNames == nil) {
NSString* path = [[NSBundle mainBundle] pathForResource:@"cityData" ofType:@"plist"];
_cityNames = [NSDictionary dictionaryWithContentsOfFile:path];
}
return _cityNames;
}
/**
* 懶加載省份
*
* @return 省份對(duì)應(yīng)的數(shù)組
*/
- (NSArray*)provinces
{
if (_provinces == nil) {
//將省份保存到數(shù)組中 但是字典保存的是無序的 所以讀出來的省份也是無序的
_provinces = [self.cityNames allKeys];
}
return _provinces;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//設(shè)置默認(rèn)選中的省份是provinces中的第一個(gè)元素
self.selectedProvince = self.provinces[0];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/**
* 返回每一列的行數(shù)
*
* @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;
}
/**
* 選中某一行后回調(diào) 聯(lián)動(dòng)的關(guān)鍵
*
* @param pickerView
* @param row 用戶選擇的省份
* @param component
*/
- (void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0) {
//選中的省份
self.selectedProvince = self.provinces[row];
//重新加載第二列的數(shù)據(jù)
[pickerView reloadComponent:1];
//讓第二列歸位
[pickerView selectRow:0 inComponent:1 animated:YES];
}
}
@end
實(shí)現(xiàn)效果
附件
plist文件下載地址:http://pan.baidu.com/s/1dETRthZ