IOS-封裝彈出框
1.封裝彈出框,包括設定彈出介面 設定彈出地點 彈出 消失等方法。大概封裝如下
#import @interface WBDropdownMenu : UIView@property (nonatomic,strong) UIView *contentView;@property (nonatomic,strong) UIViewController *cntController;+(instancetype)menu;-(void)showFrom:(UIView *)view;-(void)dismiss;@end
2.其實現如下:
#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;}#pragme 初始化透明背景介面 和彈出框背景- (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];}#pragme 設定彈出框內容-(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];}#pragme 擴充內容view的另一種形式viewController-(void)setCntController:(UIViewController *)cntController{ _cntController=cntController; [self setContentView:_cntController.view];}#pragme 設定顯示位置 該位置為windiow的絕對位置-(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
3.調用如下:
self.menu=[WBDropdownMenu menu]; WBDropdownViewController *tableViewController=[[WBDropdownViewController alloc] init]; tableViewController.tableView.height=44*3; [self.menu setCntController:tableViewController]; [self.menu showFrom:target];
(大部分彈出框顯示為當前最前的window的內容,ios8中開始預設提供一個鍵盤window)