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

iOS 開發實戰:UIPickerView 滾動選擇器的完整添加流程

編輯:iOS 開發綜合

UIPickerView 是 iOS 裡最典型的「滾輪式」選擇控件,常用於挑選性別、城市、日期這類離散選項。它的交互直觀、佔地小,是替代下拉列表的常見方案。本文從尺寸特性講起,把創建、數據綁定、代理方法到多列聯動的完整鏈路梳理一遍。

一、先認識尺寸與核心屬性

UIPickerView 的尺寸由系統固定,無法自由拉伸:縱屏下為 320 × 216,橫屏下為 568 × 162。這一點和 UITableView 完全不同,設計界面時要提前留出空間。

它的常用聲明如下:

@property(nonatomic, readonly) NSInteger numberOfComponents;   // 列數(只讀)
@property(nonatomic, assign) id<UIPickerViewDataSource> dataSource;   // 數據源,角色類似 UITableView
@property(nonatomic, assign) id<UIPickerViewDelegate> delegate;       // 代理,角色類似 UITableView

@property(nonatomic, assign) 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 - Picker Data Source

// 返回列數
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

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

#pragma mark - Picker Delegate

// 返回每一行顯示的文本
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    return [pickerData objectAtIndex:row];
}

邏輯很直白:第一個方法決定「有幾列」,第二個決定「每列幾行」,第三個決定「每行寫什麼」。本例只有一列,因此直接返回數組元素個數即可。

五、兩個協議的實例方法一覽

UIPickerViewDelegate

// 用戶選中某一行時回調
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component;

// 需要知道某行高度時回調
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component;

// 返回指定行顯示的純文本
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;

// 需要自定義行視圖時回調,返回值即作為該行內容
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row
           forComponent:(NSInteger)component reusingView:(UIView *)view;

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

UIPickerViewDataSource

按官方文檔的說法,這個協議職責非常單一:只負責告訴滾輪有幾列、每列幾行。雖然名字叫 dataSource,但它實際承擔的是 MVC 中 Controller 的角色。兩個方法都是必須實現的:

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

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

六、讀取當前選中項

按鈕的創建與事件綁定前面已經寫過,這裡只看回應方法:

- (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];
}

關鍵在 selectedRowInComponent:,它返回指定列當前選中的行號,再用行號去數組中取值即可。

七、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; // 取得某行視圖

八、進階:多列聯動

很多業務場景需要多列,而且列與列之間存在依賴關係。最典型的就是省市级聯:選了省份,城市列表要跟著變。下面以兩列為例。

在 titleForRow: 中,根據第一列當前的選中行決定第二列的文本:

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
              forComponent:(NSInteger)component
{
    // 第 0 列直接取自己的數據;第 1 列則依賴第 0 列的選擇結果
}

只做到這一步會發現一個問題:切換省份後,城市列並不會即時更新。原因很簡單——滾輪不會自動重新詢問第二列的數據,需要手動觸發刷新:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
           inComponent:(NSInteger)component
{
    [pickerView reloadComponent:1];   // 第 0 列變化後,重載第 1 列
}

把「數據準備」與「主動 reload」兩件事配起來,多列聯動就成立了。若列數更多,只需在 didSelectRow: 中判斷是哪一列發生變化,再重載其下游列即可。

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