城市選擇器是很典型的兩列聯動需求:第一列是省份,第二列是該省份對應的城市。資料放在 plist 裡,結構為「上層 Dictionary + 每個省份對應一個城市 Array」。

從元件庫拖一個 UIPickerView 到場景上,然後把它的 delegate 與 dataSource 都連到當前控制器:

#import "ViewController.h"
@interface ViewController () <UIPickerViewDelegate, UIPickerViewDataSource>
/** plist 對應的字典 */
@property (nonatomic, strong) NSDictionary *cityNames;
/** 省份 */
@property (nonatomic, strong) NSArray *provinces;
/** 城市 */
@property (nonatomic, strong) NSArray *cities;
@end
@implementation ViewController
/** 懶載入 plist */
- (NSDictionary *)cityNames {
if (_cityNames == nil) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"cityData" ofType:@"plist"];
_cityNames = [NSDictionary dictionaryWithContentsOfFile:path];
}
return _cityNames;
}
/** 懶載入省份列表 */
- (NSArray *)provinces {
if (_provinces == nil) {
_provinces = [self.cityNames allKeys];
}
return _provinces;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 2;
}
/** 每一列的行數 */
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (component == 0) {
return self.provinces.count;
} else {
[self loadData:pickerView];
return self.cities.count;
}
}
/** 每一行顯示的文字 */
- (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];
}
}
/** 依當前選中的省份載入第二列資料 */
- (void)loadData:(UIPickerView *)pickerView {
// 必須先取得使用者選中的那一列,才能知道對應的省份,
// 再用省份作為 key 從字典中取出城市列表
NSInteger selRow = [pickerView selectedRowInComponent:0];
NSString *key = self.provinces[selRow];
self.cities = [self.cityNames valueForKey:key];
}
/** 選中某一列後的回呼——聯動的關鍵 */
- (void)pickerView:(UIPickerView *)pickerView
didSelectRow:(NSInteger)row
inComponent:(NSInteger)component {
if (component == 0) {
// 重新載入第二列
[pickerView reloadComponent:1];
// 讓第二列回到頂部
[pickerView selectRow:0 inComponent:1 animated:YES];
}
}
@end聯動的核心順序不能顛倒。必須先取得第一列當前選中的行號,換算出省份名稱,才能拿它當 key 去字典裡取城市列表。這也是為什麼 numberOfRowsInComponent: 和 titleForRow: 中都要先呼叫一次 loadData:——系統詢問第二列的行數與文字時,我們得保證 cities 已經是最新狀態。
記得重置第二列。用戶選了新省份後,除了 reloadComponent:,最好再呼叫 selectRow:0 inComponent:1 animated:YES 把第二列歸位,否則可能停留在舊位置的索引上,甚至超出新列表範圍而崩潰。
用懶載入攤平成本。plist 只在第一次真正需要時才讀入,並透過 cityNames 與 provinces 兩個 getter 快取起來,避免反覆解析檔案。

本文整理自 YungFan 的簡書。