下拉選單是 App 裡最基礎也最常見的元件之一。iOS 並沒有現成的下拉選單控件,因此我們需要自己組合:一個觸發按鈕,加上一個由多個 UIButton 組成的清單 view,再透過 hidden 屬性控制展開與收合。本文示範如何把它封裝成可重複使用的方法。
- (void)createMeunView {
UIButton *showMeunViewButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
showMeunViewButton.center = self.view.center;
[showMeunViewButton setTitle:@"顯示菜單" forState:UIControlStateNormal];
[showMeunViewButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[showMeunViewButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
[showMeunViewButton addTarget:self action:@selector(showMeunViewButtonAction:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:showMeunViewButton];
showMeunView = [self createMeunView:showMeunViewButton
buttonTitles:@[@"1", @"2", @"3", @"4", @"5"]
menuButtonTagStart:300];
[self.view addSubview:showMeunView];
}
- (void)showMeunViewButtonAction:(UIButton *)button {
button.selected = !button.selected;
if (button.selected) {
showMeunView.hidden = NO;
} else {
showMeunView.hidden = YES;
}
}
#pragma mark -- 封裝建立選單的方法
- (UIView *)createMeunView:(UIButton *)button
buttonTitles:(NSArray *)buttonTitles
menuButtonTagStart:(NSInteger)tagStart {
// button : 選單顯示在這個按鈕下方
// buttonTitles : 選單按鈕的標題陣列
// tagStart : 選單按鈕 tag 起始值,用於區分點了哪一個
UIView *menuView = [[UIView alloc] initWithFrame:
CGRectMake(button.minX, button.maxY, button.width, 41 * buttonTitles.count)];
menuView.hidden = YES;
menuView.backgroundColor = [UIColor blackColor];
for (int i = 0; i < buttonTitles.count; i++) {
UIButton *menuButton = [[UIButton alloc] initWithFrame:
CGRectMake(0, 41 * i, menuView.width, 40)];
menuButton.backgroundColor = [UIColor brownColor];
[menuButton setTitle:buttonTitles[i] forState:UIControlStateNormal];
menuButton.titleLabel.font = FONT(14);
[menuButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[menuButton addTarget:self action:@selector(menuButtonAction:)
forControlEvents:UIControlEventTouchUpInside];
menuButton.tag = tagStart + i;
[menuView addSubview:menuButton];
}
return menuView;
}
- (void)menuButtonAction:(UIButton *)button {
NSLog(@"%lu", button.tag);
}

menuButtonTagStart 讓同一個 menuButtonAction: 能服務所有項目,點擊時再用 button.tag - tagStart 反推索引,避免為每個按鈕寫一個方法。button.minX / maxY / width 讓選單自動對齊在觸發按鈕的正下方且同寬,按鈕換位置時選單無需另外調整。createMeunView:buttonTitles:menuButtonTagStart:,標題與起始 tag 都參數化,之後任何頁面都能直接複用。這個版本是最小可用實作,若要投入 production,建議補上:點擊選單項目後自動收合、選中項目在選單中顯示勾選狀態、加上展開收合的過場動畫,以及點擊外部區域時關閉選單(可加入一個透明遮罩 view 來接收事件)。