UIPickerView 平常用到的機會不算多,但一旦需要「點一下跳出選擇器」的互動,就得自己封裝。本文做一個可直接複用的 YLSPicker,示範單選、兩欄聯動、以及帶隨機按鈕的三種變體。
先看成果:

最初版本:

這個 demo 幾乎可以當成現成的元件用,只要傳資料進去。三個彈出框顯示的資料不同,但因為我不太會抽象,就各自寫了一份。完整專案在 GitHub:YLSPicker。
畫面上擺三個不能輸入的 UITextField,點擊就彈出對應的選擇器。
// 巨集定義
#define YLSRect(x, y, w, h) CGRectMake([UIScreen mainScreen].bounds.size.width * x, [UIScreen mainScreen].bounds.size.height * y, [UIScreen mainScreen].bounds.size.width * w, [UIScreen mainScreen].bounds.size.height * h)
@interface ViewController () <UITextFieldDelegate>
/** text1 */
@property (nonatomic, strong) UITextField *text1;
/** text2 */
@property (nonatomic, strong) UITextField *text2;
/** text3 */
@property (nonatomic, strong) UITextField *text3;
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Picker";
// placeholder 陣列
NSArray *placeholderArr = @[@"Picker OneVlaue", @"Picker TwoVlaue", @"Picker ThreeVlaue"];
// 迴圈加入三個文字框
for (int i = 0; i < 3; i++) {
UITextField *text = [[UITextField alloc] initWithFrame:YLSRect(100/375, (140 + i * 60)/667, 175/375, 30/667)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.backgroundColor = [UIColor lightGrayColor];
text.tag = i + 1000;
text.placeholder = placeholderArr[i];
text.delegate = self;
[self.view addSubview:text];
if (text.tag == 1000) {
self.text1 = text;
} else if (text.tag == 1001) {
self.text2 = text;
} else {
self.text3 = text;
}
}
}
很多人對 UITextField 的代理不熟,會問:「點擊文字框但不進入編輯,同時彈出自訂 view,這件事該寫在哪?」答案就是這個方法:
// 點擊文字框時觸發的事件 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;
回傳 NO,系統就不會彈出鍵盤,控制权完全交回給你。
1. 建立類別 YLSOPickerView。
2. 在 .h 中宣告要傳入的陣列與標題,以及兩個方法:
@interface YLSOPickerView : UIView /** array */ @property (nonatomic, strong) NSArray *array; /** title */ @property (nonatomic, strong) NSString *title; // 快速建立 + (instancetype)pickerView; // 彈出 - (void)show; @end
3. .m 的實作。先放巨集:
#define YLSRect(x, y, w, h) CGRectMake([UIScreen mainScreen].bounds.size.width * x, [UIScreen mainScreen].bounds.size.height * y, [UIScreen mainScreen].bounds.size.width * w, [UIScreen mainScreen].bounds.size.height * h) #define YLSFont(f) [UIFont systemFontOfSize:[UIScreen mainScreen].bounds.size.width * f] #define YLSColorAlpha(r,g,b,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)] #define YLSMainBackColor [UIColor colorWithRed:240/255.0 green:239/255.0 blue:245/255.0 alpha:1] #define BlueColor [UIColor colorWithRed:0/255.0 green:122/255.0 blue:255/255.0 alpha:1] #define ClearColor [UIColor clearColor]
宣告元件並遵守 UIPickerView 的兩個協議:
@interface YLSOPickerView () <UIPickerViewDelegate, UIPickerViewDataSource> /** view */ @property (nonatomic, strong) UIView *topView; /** button */ @property (nonatomic, strong) UIButton *doneBtn; /** pickerView */ @property (nonatomic, strong) UIPickerView *pickerView; /** 選擇回傳的值 */ @property (nonatomic, strong) NSString *result; @end
初始化:
// 快速建立
+ (instancetype)pickerView {
return [[self alloc] init];
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:YLSRect(0, 0, 1, 917/667)];
if (self) {
self.backgroundColor = YLSColorAlpha(0, 0, 0, 0.4);
}
return self;
}
這裡有個小技巧:為了做出「從下方滑上來」的效果,我把整個 view 的高度設成「一個螢幕 + 選擇器高度」,然後在 show 方法中讓它整體上移後才加入畫面。
版面配置:
- (void)layoutSubviews {
[super layoutSubviews];
self.topView = [[UIView alloc] initWithFrame:YLSRect(0, 667/667, 1, 250/667)];
self.topView.backgroundColor = [UIColor whiteColor];
[self addSubview:self.topView];
// 把 view 的左上、右上兩角做成圓角,不喜歡可以註解掉
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.topView.bounds
byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight
cornerRadii:CGSizeMake(5, 5)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.topView.bounds;
maskLayer.path = maskPath.CGPath;
self.topView.layer.mask = maskLayer;
self.doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.doneBtn setTitle:@"Done" forState:UIControlStateNormal];
[self.doneBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[self.doneBtn setFrame:YLSRect(320/375, 5/667, 50/375, 40/667)];
[self.doneBtn addTarget:self action:@selector(quit) forControlEvents:UIControlEventTouchUpInside];
[self.topView addSubview:self.doneBtn];
UILabel *titlelb = [[UILabel alloc] initWithFrame:YLSRect(100/375, 0, 175/375, 50/667)];
titlelb.backgroundColor = ClearColor;
titlelb.textAlignment = NSTextAlignmentCenter;
titlelb.text = self.title;
titlelb.font = YLSFont(20/375);
[self.topView addSubview:titlelb];
self.pickerView = [[UIPickerView alloc] init];
[self.pickerView setFrame:YLSRect(0, 50/667, 1, 200/667)];
[self.pickerView setBackgroundColor:YLSMainBackColor];
[self.pickerView setDelegate:self];
[self.pickerView setDataSource:self];
[self.pickerView selectRow:0 inComponent:0 animated:YES];
[self.topView addSubview:self.pickerView];
}
UIPickerView 的協議方法:
// 回傳選擇器有幾欄
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
// 回傳每組有幾列
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [self.array count];
}
#pragma mark - 代理
// 回傳第 component 欄第 row 列的內容(標題)
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return self.array[row];
}
// 選中第 component 欄第 row 列時呼叫
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
self.result = self.array[row];
}
彈出與關閉:
// 彈出
- (void)show {
[self showInView:[UIApplication sharedApplication].keyWindow];
}
// 加入彈出/移除的動畫效果
- (void)showInView:(UIView *)view {
[UIView animateWithDuration:0.5 animations:^{
CGPoint point = self.center;
point.y -= 250;
self.center = point;
} completion:^(BOOL finished) {
}];
[view addSubview:self];
}
- (void)quit {
[UIView animateWithDuration:0.5 animations:^{
self.alpha = 0;
CGPoint point = self.center;
point.y += 250;
self.center = point;
} completion:^(BOOL finished) {
if (!self.result) {
self.result = self.array[0];
}
NSLog(@"%@", self.result);
[[NSNotificationCenter defaultCenter] postNotificationName:@"value" object:self.result];
[self removeFromSuperview];
}];
}
這裡要注意:如果使用者既沒點擊也沒滑動,self.result 會是 nil,所以要判斷一下,為空時帶回陣列第一筆。
另外我用的是通知傳值,因為當時還沒學 block。順帶回答原文的提問:通知一般在 dealloc 中移除,或者更精準的做法是在接收方的生命週期結束點移除;不過在 iOS 9 之後,NSNotificationCenter 會自動對 selector 式的 observer 做弱引用管理,不移除也不會 crash,只是仍建議明確移除以免多餘回呼。
引入標頭:
#import "YLSOPickerView.h"
#pragma mark - UITextFieldDelegate
// 點擊文字框時觸發,喚起跳出視圖
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if (textField.tag == 1000) {
YLSOPickerView *picker = [[YLSOPickerView alloc] init];
picker.array = @[@"iPhone4", @"iPhone4S", @"iPhone5", @"iPhone5S", @"iPhone5C",
@"iPhone6", @"iPhone6Plus", @"iPhone6S", @"iPhone6SPlus"];
picker.title = @"pick number";
[picker show];
}
return NO;
}
在 viewDidLoad 註冊通知並實作接收方法:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getValue:) name:@"value" object:nil];
- (void)getValue:(NSNotification *)notification {
self.text1.text = notification.object;
}
這樣一個簡單的單選彈出式選擇器就完成了。
第二個文字框:兩欄聯動。本質與上面相同,只是傳入的資料改成字典,再用兩個陣列分別接住兩欄的內容,然後在 didSelectRow 中依第一欄的選擇去更新第二欄的資料並呼叫 reloadComponent:。
第三個文字框:加上隨機按鈕。
self.ranBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [self.ranBtn setTitle:@"Random" forState:UIControlStateNormal]; [self.ranBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; [self.ranBtn setFrame:YLSRect(5/375, 5/667, 100/375, 40/667)]; [self.ranBtn addTarget:self action:@selector(random:) forControlEvents:UIControlEventTouchUpInside]; [self.topView addSubview:self.ranBtn];
- (void)random:(UIPickerView *)picker {
for (int i = 0; i < 3; i++) {
// 取出第 i 欄的列數
NSInteger count = [self.array[i] count];
int random = arc4random_uniform((u_int32_t)count);
// 不會觸發代理的選中方法
[self.pickerView selectRow:random inComponent:i animated:YES];
// 手動刷新 label 資料
[self pickerView:picker didSelectRow:random inComponent:i];
}
}
這裡有個值得記住的細節:selectRow:inComponent:animated: 不會觸發 didSelectRow,所以程式化選取之後必須自己補一次資料同步,否則畫面選中的和實際回傳的值會不一致。