城市選擇器,借助於UIPickerView來實現,第一列為省份,第二列為第一列省份對應的城市或者區,數據放在plist中,plist結構如下圖所示,第一層是一個Dictionary,每個省份對應的城市是一個Array:
拖入一個UIPickerView到StoryBoard中,然後設置UIPickerViewDelegate,和UIPickerViewDataSource為當前的控制器,如下圖紅色區域所示:
設置數據源與代理.png在對應的ViewController中進行實現,代碼注釋非常詳細
#import "ViewController.h" @interface ViewController ()/** * plist對應的字典 */ @property (nonatomic, strong) NSDictionary* cityNames; /** * 省份 */ @property (nonatomic, strong) NSArray* provinces; /** * 城市 */ @property (nonatomic, strong) NSArray* cities; @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]; // Do any additional setup after loading the view, typically from a nib. } - (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 loadData:pickerView]; 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 loadData:pickerView]; return self.cities[row]; } } /** * 加載第二列顯示的數據 * * @param pickerView */ -(void)loadData:(UIPickerView*)pickerView { //一定要首先獲取用戶選擇的那一行 然後才可以根據選中行獲取省份 獲取省份以後再去字典中加載省份對應的城市 NSInteger selRow = [pickerView selectedRowInComponent:0]; NSString *key = self.provinces[selRow]; self.cities = [self.cityNames valueForKey:key]; } /** * 一共多少咧 * * @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) { //重新加載第二列的數據 [pickerView reloadComponent:1]; //讓第二列歸位 [pickerView selectRow:0 inComponent:1 animated:YES]; } } @end