創建全屏幕的彈出視圖
- 自定義一個View繼承與UIWindow
- 重寫init方法
static AlertWindow *singleInstance;
-(instancetype)init
{
if (self = [super initWithFrame:[UIScreen mainScreen].bounds]) {
self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
self.windowLevel = UIWindowLevelAlert - 1;
singleInstance = self;
}
return self;
}
- windowLevel(window層級)
//總共三種 默認為Nomal
UIKIT_EXTERN const UIWindowLevel UIWindowLevelNormal;//0
UIKIT_EXTERN const UIWindowLevel UIWindowLevelAlert;//2000
UIKIT_EXTERN const UIWindowLevel UIWindowLevelStatusBar//1000
將windowLevel設為UIWindowLevelAlert - 1確保出現在最上層
-
設置contentView用來顯示需要的內容
_contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width - 80, 200)];
_contentView.backgroundColor = [UIColor whiteColor];
[_contentView setCenter:CGPointMake(self.bounds.size.width / 2, self.bounds.size.height /2 )];
[self addSubview:_contentView];UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _contentView.frame.size.width, 150)]; label.textAlignment = NSTextAlignmentCenter; label.text = @"show the window"; label.textColor = [UIColor blackColor]; [_contentView addSubview:label]; UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 149, _contentView.frame.size.width, 1)]; line.backgroundColor = [UIColor blackColor]; [_contentView addSubview:line]; UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(0, 150, _contentView.frame.size.width, 50); [button setTitle:@"Done" forState:UIControlStateNormal]; [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; [button addTarget:self action:@selector(hideWithAnimation) forControlEvents:UIControlEventTouchUpInside]; [_contentView addSubview:button]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideWithAnimation)]; [self addGestureRecognizer:tap]; UITapGestureRecognizer *other = [[UITapGestureRecognizer alloc] init]; [_contentView addGestureRecognizer:other];
- 為self添加tap手勢,在點擊黑色背景的時候調用hide方法關閉視圖
- 為contentView添加tap手勢,覆蓋掉self上的手勢,避免點擊contentView范圍調用hide方法
- 添加show和hide方法
-(void)showWithAnimation:(BOOL)animation
{
[self makeKeyAndVisible];
[UIView animateWithDuration:animation ? 0.3 : 0
animations:^{
}
completion:^(BOOL finished) {
}];
}
-(void)hideWithAnimation:(BOOL)animation
{
[UIView animateWithDuration:animation ? 0.3 : 0
animations:^{
self.alpha = 0;
}
completion:^(BOOL finished) {
singleInstance = nil;
}];
}
- 重寫dealloc方法調用resignKeyWindow
-(void)dealloc
{
[self resignKeyWindow];
}
運用這個方法可以實現一些自定義的彈出視圖
github
Demo已上傳到github 地址