您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS UIPickerView 滾動選擇器詳解:多欄資料綁定與聯動刷新

編輯:iOS 相關教學

UIPickerView 是那種「一看就懂、一寫就忘」的元件——畫面上只是一個滾筒,但要讓它正確顯示資料並回報選擇結果,得同時實作兩個協定。本文把尺寸限制、屬性、資料來源與代理方法一次講清楚,最後示範多欄聯動(例如省份與城市)該怎麼做。

一、尺寸與基本屬性

首先要知道一個限制:UIPickerView 的寬高是固定的,無法任意縮放。縱向(iPhone 直式)為 320 × 216,橫向為 568 × 162。

@property (nonatomic, readonly) NSInteger numberOfComponents;              // 選擇框的列數

@property (nonatomic, assign) id<UIPickerViewDataSource> dataSource;      // 資料來源,概念近似 UITableView
@property (nonatomic, assign) id<UIPickerViewDelegate> delegate;          // 代理,同樣近似 UITableView

- (BOOL)showsSelectionIndicator;   // 是否顯示選中指示器,也就是那條藍色的框

最基礎的建立程式碼:

pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 216)];

pickerView.delegate = self;                 // 指定代理
pickerView.showsSelectionIndicator = YES;   // 顯示選中框
[self.view addSubview:pickerView];

此時執行可以看到一個空白的選取器。之所以空白,是因為還沒提供任何資料——這正是下一節要解決的問題。

二、宣告協定與初始化資料

要在選取器上顯示內容,必須依賴 UIPickerViewDelegate 與 UIPickerViewDataSource 兩個協定。先在頭檔中宣告:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {
    UIPickerView *pickerView;
    NSArray *pickerData;
}

@end

接著在 viewDidLoad 中完成介面與資料的初始化,順手加一顆按鈕用來讀取目前選擇:

- (void)viewDidLoad {
    [super viewDidLoad];

    pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 216)];
    pickerView.delegate = self;
    pickerView.showsSelectionIndicator = YES;
    [self.view addSubview:pickerView];

    NSArray *dataArray = [[NSArray alloc] initWithObjects:
                          @"許嵩", @"周杰倫", @"梁靜茹", @"許飛", @"鳳凰傳奇",
                          @"阿杜", @"方大同", @"林俊傑", @"胡夏", @"邱永傳", nil];
    pickerData = dataArray;

    // 加上一顆確認按鈕
    CGRect frame = CGRectMake(120, 250, 80, 40);
    UIButton *selectButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    selectButton.frame = frame;
    [selectButton setTitle:@"SELECT" forState:UIControlStateNormal];
    [selectButton addTarget:self
                     action:@selector(buttonPressed:)
           forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:selectButton];
}

三、實作資料來源與代理方法

#pragma mark -
#pragma mark Picker Data Source Methods

// 回傳列數:有幾個選擇器就回傳幾
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

// 回傳當前列的行數
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [pickerData count];
}

#pragma mark Picker Delegate Methods

// 回傳當前行的顯示文字
- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
             forComponent:(NSInteger)component {
    return [pickerData objectAtIndex:row];
}

三個方法的分工很清楚:第一個決定有幾列,第二個決定每列有幾行,第三個決定每一行顯示什麼。資料來源(DataSource)負責前兩個「數量」問題,代理(Delegate)負責「內容」與「互動」問題。

兩個協定的方法對照

UIPickerViewDelegate 的實例方法:

// 使用者選定某一 row 時呼叫
- (void)pickerView:(UIPickerView *)pickerView
        didSelectRow:(NSInteger)row
         inComponent:(NSInteger)component;

// 需要知道 row 高度時呼叫
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component;

// 回傳指定 component.row 顯示的文字
- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component;

// 需要自訂 row 的 view 時呼叫
- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)view;

// row 的寬度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component;

UIPickerViewDataSource 的實例方法:依官方文件說明,這個協定的唯一職責就是提供「有幾列」與「每列有幾行」,兩個方法都必須實作。有趣的一點是:它雖名為 DataSource,實際運作位置卻是在 MVC 的 Controller 層。

// 回傳列數
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;

// 回傳每一列對應的行數
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;

四、讀取並使用目前選項

按下按鈕時,用 selectedRowInComponent: 取得索引,再回頭查資料陣列即可:

- (void)buttonPressed:(id)sender {
    NSInteger row = [pickerView selectedRowInComponent:0];
    NSString *selected = [pickerData objectAtIndex:row];
    NSString *message = [[NSString alloc] initWithFormat:@"你選擇的是:%@", selected];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:message
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}

UIPickerView 其他常用方法

- (NSInteger)numberOfRowsInComponent:(NSInteger)component;              // 取得指定列的行數
- (void)reloadAllComponents;                                            // 刷新所有列
- (void)reloadComponent:(NSInteger)component;                           // 刷新指定列
- (CGSize)rowSizeForComponent:(NSInteger)component;
- (NSInteger)selectedRowInComponent:(NSInteger)component;               // 取得某列目前選中的行
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated;   // 程式化選取
- (UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)component;

五、進階:多欄資料聯動

實務上常見「省份 + 城市」這種兩欄聯動需求:左欄選省份,右欄的城市要跟著變。假設 component 數量為 2,做法是在 titleForRow 中,依據第 0 欄目前選中的行決定第 1 欄該顯示什麼:

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component {
    // 依 component 與 selectedRowInComponent:0 決定回傳內容
}

但只這樣寫會發現一個問題:切換省份後,城市欄並不會即時更新。這是因為 UIPickerView 不會自動重繪其他欄,我們得在選擇事件裡手動觸發刷新:

- (void)pickerView:(UIPickerView *)pickerView
        didSelectRow:(NSInteger)row
         inComponent:(NSInteger)component {
    [pickerView reloadComponent:1];
}

加上這一行,兩欄聯動就完整了。掌握「DataSource 管數量、Delegate 管內容、reloadComponent 管刷新」這三條主線,UIPickerView 就不難了。

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