您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 省市區三級選擇器實作(以 UITableView 取代 PickerView)

編輯:iOS 開發綜合

在 iOS 專案中,地區選擇器(省/市/區)是很常被要求的功能。Android 平台下已經有成熟的自訂 Dialog 可用;iOS 這邊網路上多數範例採用 UIPickerView,把省市區分成三欄。

那種做法效果不錯,但有幾個明顯缺點:區名較長時會被截斷看不全、沒有確定的按鈕可點、而且使用者無法自行輸入地址。

因此這裡改用 UITableView 實作:一格一層,點選省分後列表換成該省的縣市,再點選縣市後換成區,最後在上方以 UITextField 即時顯示目前選擇的完整路徑,並允許使用者直接鍵盤輸入。這樣既有清楚的層級視覺,也解決了文字過長與無法手動輸入的問題。

一、頭檔案設計

#import <UIKit/UIKit.h>

// 目前的選擇層級
typedef enum {
    PROVINCE,
    CITY,
    AREA
} NerveSelectoreType;

// 選擇器協定,呼叫方實作此協定即可接收結果
@protocol NerveAreaSelectDelegate <NSObject>
@optional
- (void)onAreaSelect:(NSString *)selectValue;
- (void)onAreaCannel;
@end

@interface NerveAreaSelectorViewController : UIViewController
    <UITableViewDataSource, UITableViewDelegate> {
    NSArray *provinces, *cities, *areas;
    NSString *province, *city, *area;
    NSInteger selectType;   // 當前選擇類型
}

@property (weak, nonatomic) IBOutlet UITextField *areaTX;
@property (weak, nonatomic) IBOutlet UITableView *areaTableView;

-(id)initWithDelegate:(id<NerveAreaSelectDelegate>)targetDelegate;
- (IBAction)onOkBtnClick:(id)sender;
- (IBAction)okCannelBtnClick:(id)sender;
- (IBAction)exitInput:(id)sender;
@end

二、初始化與載入資料

-(id)initWithDelegate:(id<NerveAreaSelectDelegate>)targetDelegate {
    delegate = targetDelegate;
    [self readData];        // 讀取 JSON/plist 並組出 provinces 陣列
    selectType = PROVINCE;  // 預設從省分開始
    return self;
}

資料結構採嵌套設計:provinces 中每一筆有 state 與 cities,cities 中每一筆有 city 與 areas,areas 則是純字串陣列。

三、產生 Cell

依目前所在的層級決定要顯示哪個陣列的哪個欄位,省與市階層加上可展開的箭頭:

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    int index = [indexPath row];
    static NSString* cellID = @"NerveAreaSelectorCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                    reuseIdentifier:cellID];
    }

    switch (selectType) {
        case PROVINCE:
            cell.textLabel.text = [[provinces objectAtIndex:index] objectForKey:@"state"];
            cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
            break;
        case CITY:
            cell.textLabel.text = [[cities objectAtIndex:index] objectForKey:@"city"];
            cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
            break;
        default:
            cell.textLabel.text = [areas objectAtIndex:index];
            cell.accessoryType = UITableViewCellAccessoryNone;
            break;
    }
    return cell;
}

四、點選後往下鑽

這是整个元件的核心邏輯:選省分就載入對應的縣市列表,選縣市就載入區列表,選到區則完成:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int selectIndex = [indexPath row];
    int cellCount = 0;

    switch (selectType) {
        case PROVINCE:
            province = [[provinces objectAtIndex:selectIndex] objectForKey:@"state"];
            cities   = [[provinces objectAtIndex:selectIndex] objectForKey:@"cities"];
            selectType = CITY;
            cellCount = [cities count];
            break;
        case CITY:
            city  = [[cities objectAtIndex:selectIndex] objectForKey:@"city"];
            areas = [[cities objectAtIndex:selectIndex] objectForKey:@"areas"];
            selectType = AREA;
            cellCount = [areas count];
            break;
        default:
            area = [areas objectAtIndex:selectIndex];
            break;
    }

    NSString *areaValue = [NSString stringWithFormat:@"%@ %@ %@", province, city, area];
    self.areaTX.text = areaValue;

    [areaTableView reloadData];

    // 若有下一層資料,捲回頂端方便繼續選擇
    if (cellCount > 0) {
        NSIndexPath *top = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
        [areaTableView scrollToRowAtIndexPath:top
                            atScrollPosition:UITableViewScrollPositionTop
                                    animated:YES];
    }
}

五、確定與取消

- (IBAction)onOkBtnClick:(id)sender {
    [delegate onAreaSelect:areaTX.text];   // 回傳完整地址字串
}

- (IBAction)okCannelBtnClick:(id)sender {
    [delegate onAreaCannel];
}

呼叫方只要實作 NerveAreaSelectDelegate,就能在 onAreaSelect: 中拿到「XX省 YY市 ZZ區」這樣的完整字串。

幾點改善建議

這個實作以「切換資料來源 + reload」的方式模擬層級鑽取,程式碼單純、效能也好,但仍有改進空間:

1. 在 navigation bar 上顯示目前層級與返回按鈕,讓使用者能回上一層,而不必重新選起;

2. 為 areaTX 加入 shouldChangeCharactersInRange 的過濾,限制只能輸入中文,並同步更新按鈕的 enable 狀態;

3. 把省/市/區資料改成從 bundle 中的 JSON 讀取並做一次性快取,避免每次開啟選擇器都重新解析;

4. 若只需要單純選擇而不需要手動輸入,其實 iOS 8 以後的 UIPickerView 加上 titleForRow 回傳完整字串(而非依賴欄寬)也能解決文字截斷的問題,實作成本更低。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved