下拉式選單在 iOS 上沒有系統原生控件,幾乎每個專案都得自己刻一次。既然要做,就一次封裝好,讓呼叫端只要三行就能用。
封裝目標很明確:設定內容、指定彈出位置、顯示、關閉。
#import <UIKit/UIKit.h>
@interface WBDropdownMenu : UIView
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIViewController *cntController;
+ (instancetype)menu;
- (void)showFrom:(UIView *)view;
- (void)dismiss;
@end
整體結構是:一個鋪滿全螢幕的透明容器負責接收「點擊外部關閉」,上面疊一張背景圖作為彈出框本體。
#import "WBDropdownMenu.h"
@interface WBDropdownMenu ()
@property (nonatomic, weak) UIImageView *containerView;
@end
@implementation WBDropdownMenu
// 彈出框背景,懶載入
- (UIImageView *)containerView {
if (!_containerView) {
UIImageView *iv = [[UIImageView alloc] init];
iv.image = [UIImage imageNamed:@"popover_background"];
iv.width = 217;
[self addSubview:iv];
_containerView = iv;
}
return _containerView;
}
// 初始化:鋪滿螢幕、背景透明
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.frame = [UIScreen mainScreen].bounds;
self.backgroundColor = [UIColor clearColor];
[self containerView].userInteractionEnabled = YES;
}
return self;
}
+ (instancetype)menu {
return [[WBDropdownMenu alloc] init];
}
// 設定內容,並依內容高度撐開背景
- (void)setContentView:(UIView *)contentView {
contentView.x = 10;
contentView.y = 15;
contentView.width = self.containerView.width - 2 * contentView.x;
self.containerView.height = CGRectGetMaxY(contentView.bounds) + 25;
[self.containerView addSubview:contentView];
}
// 點到外部就關閉
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self dismiss];
}
// 也支援直接傳入 ViewController,取其 view 作為內容
- (void)setCntController:(UIViewController *)cntController {
_cntController = cntController;
[self setContentView:_cntController.view];
}
// 定位:傳入的 view 座標會被轉為 window 的絕對座標
- (void)showFrom:(UIView *)view {
UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
[window addSubview:self];
CGRect absRect = [view convertRect:view.bounds toView:self];
self.containerView.y = CGRectGetMaxY(absRect);
self.containerView.midX = CGRectGetMidX(absRect);
}
- (void)dismiss {
[self removeFromSuperview];
}
@end
self.menu = [WBDropdownMenu menu];
WBDropdownViewController *tableViewController = [[WBDropdownViewController alloc] init];
tableViewController.tableView.height = 44 * 3;
[self.menu setCntController:tableViewController];
[self.menu showFrom:target];
之所以把自身加到 window 而非 caller 的 view 上,是因為大部分彈出層都應該浮在當前畫面最前方;iOS 8 之後系統本身也會為鍵盤準備獨立的 window,把彈出層掛在 window 上能避免被鍵盤遮住。
另外,這裡用「先設定內容、再由內容高度反推背景高度」的做法,能讓選單自動適配不同項目數量,不必在呼叫端手算高度。若要加上展開/收起的動畫,可在 showFrom: 末尾對 containerView 做 transform 的縮放動畫,並記得在 dismiss 中補上動畫完成後再 removeFromSuperview,否則會看不到收尾效果。