實現(xiàn)思路:
1,首先要拿到window (方式有多重可以app delegate,或者創(chuàng)建window失受、keywindow等等方式)讶泰。
2. 然后創(chuàng)建一個backgroundView,使其frame和window相等拂到,設(shè)置背景顏色痪署,再添加到window上。
3.把需要顯示的view添加到backgroundView上兄旬,當然有動畫效果更好狼犯,通過改變view的frame來實現(xiàn)view的顯示與隱藏。
代碼如下
#define SCREENWIDTH [UIScreen mainScreen].bounds.size.width
#define SCREENHEIGHT [UIScreen mainScreen].bounds.size.height
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic)UIView *bgView;//半透明背景
@property (strong, nonatomic)UIView *alertView;//假設(shè)為彈窗
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake((SCREENWIDTH-100)/2, 50, 100, 100)];
btn.backgroundColor = [UIColor yellowColor];
[self.view addSubview:btn];
[btn addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchUpInside];
}
- (void)show{
//1. 取出window
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
//2. 創(chuàng)建背景視圖
_bgView = [[UIView alloc]init];
_bgView.frame = window.bounds;
//3. 背景顏色可以用多種方法
_bgView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
// _bgView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.6];
[window addSubview:_bgView];
//4. 把需要展示的控件添加上去
_alertView = [[UIView alloc ]initWithFrame:CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, 49)];
_alertView.backgroundColor = [UIColor greenColor];
[window addSubview:_alertView];
//5. 動畫簡單(low)
[UIView animateWithDuration:0.3 animations:^{
_alertView.frame = CGRectMake(0, SCREENHEIGHT-49, SCREENWIDTH, SCREENHEIGHT);
}];
//6.給背景添加一個手勢,后續(xù)方便移除視圖
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideAlertView)];
[_bgView addGestureRecognizer:tap];
}
- (void)hideAlertView{
//動畫簡單(low)
[UIView animateWithDuration:0.3 animations:^{
_alertView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, 49);
}];
// 延遲幾秒移除視圖
[self performSelector:@selector(remove) withObject:nil afterDelay:0.3];
}
- (void)remove{
[_bgView removeFromSuperview];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end