建立首頁下拉選單,本節先完成下拉選單介面的建立,下節再微調其位置。
DJDropdownMenu.h
#import <UIKit/UIKit.h> @interface DJDropdownMenu : UIView /** 構造方法 */ + (instancetype)menu; /** 顯示 */ - (void)show; /** 消失 */ - (void)dismiss; @property (nonatomic,weak) UIView *contentView; @property (nonatomic,strong) UIViewController *contentController; @end
DJDropdownMenu.m
#import "DJDropdownMenu.h" @interface DJDropdownMenu() /** 灰色背景 */ @property (nonatomic,weak) UIImageView *containerView; @end @implementation DJDropdownMenu - (UIImageView *)containerView { if (!_containerView) { UIImageView *imageView = [[UIImageView alloc] init]; imageView.width = 217; imageView.height = 217; imageView.image = [UIImage imageNamed:@"popover_background"]; [self addSubview:imageView]; _containerView = imageView; } return _containerView; } - (void)setContentView:(UIView *)contentView { _contentView = contentView; // 1. 設定contentView位置 contentView.x = 10; contentView.y = 15; // 2. 設定contentView寬度(防止寬度過長導致圖片拉伸變形) contentView.width = self.containerView.width - 2* contentView.x; // 3. 設定containerView高度(隨contentView高度的變化而變化) self.containerView.height = CGRectGetMaxY(contentView.frame)+12; // 4.新增contentView至containerView; [self.containerView addSubview:contentView]; } - (void)setContentController:(UIViewController *)contentController { _contentController = contentController; [self setContentView:contentController.view]; } - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // 1.設定背景顏色透明 self.backgroundColor = [UIColor clearColor]; // 2.設定containerView可以與使用者互動 self.containerView.userInteractionEnabled = YES; } return self; } + (instancetype)menu { return [[self alloc] init]; } /** show即是將當前View新增到頂層視窗上 */ - (void)show { // 1. 獲取頂層視窗 UIWindow *window = [[UIApplication sharedApplication].windows lastObject]; // 2. 設定當前View大小 self.frame = window.bounds; // 3. 新增當前View到頂層視窗 [window addSubview:self]; } /** dismiss即是將當前View從頂層視窗移除 */ - (void)dismiss { [self removeFromSuperview]; } @end
最終效果: