您的位置:首页 > 产品设计 > UI/UE

iOS SDK详解之UIWindow(让视图在最上层)

2016-02-15 20:11 295 查看
这个iOS SDK详解的专栏地址

http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html

前言:

很多时候,我们希望视图显示在最上层,不管底部的层次结构如何,例如App的引导页,又比很多交易类App的弹出输入密码的提示框。

UIWindow是什么?

UIWindow继承自UIView,也就是说它本身就是一个视图的容器。通常一个App只有一个UIWindow,也就是AppDelegate中的UIWindow。UIWindow的主要作用有两个

1. 作为最顶层的视图容器,包含应用显示的所有的视图

2. 传递触摸和键盘等事件给视图

尝试使用UIWindow

- (IBAction)buttonClicked:(id)sender {
window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
window.backgroundColor = [UIColor redColor];
window.windowLevel = UIWindowLevelAlert - 1;
window.hidden = NO;
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissWindow)];
[window addGestureRecognizer:tap];
}
-(void)dismissWindow{
window.hidden = YES;
window = nil;
}


注意,UIWindow不需要像View那样进行
addSubview
添加到视图层次中,当Window创建的时候,就自动显示,通过
WindowLevel
来决多个window同时存在时候,哪个在上层,哪个在下层。

WindowLevel

系统提供的三个window level常量是

UIWindowLevelAlert
UIWindowLevelNormal
UIWindowLevelStatusBar


通过log,可以看到其实际的值

NSLog(@"%f %f %f",UIWindowLevelAlert,UIWindowLevelNormal,UIWindowLevelStatusBar);
//2000.000000 0.000000 1000.000000


window在创建的时候,默认是UIWindowLevelNormal(0.0),这个值越大,层次越靠上,也就是说

windowLevel大于0,小于1000的时候,在statusbar之下,在默认的window之上

windowLevel大于1000的时候,就在statusbar之上了。

rootViewController

UIWindow的rootViewController为Window提供可视部分。例如如下代码,创建一个Statusbar部分可见的效果



@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = [UIScreen mainScreen].bounds.size.height;;
UIView * subview = [[UIView alloc] initWithFrame:CGRectMake(width/2,0,width/2,height)];
subview.backgroundColor = [UIColor redColor];
[self.view addSubview:subview];
// Do any additional setup after loading the view.
}

@end


然后,创建一个以SecondViewController为根视图的Window

- (IBAction)buttonClicked:(id)sender {
window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
window.windowLevel =  UIWindowLevelStatusBar + 1;
window.hidden = NO;
SecondViewController * rvc = [[SecondViewController alloc] init];
window.rootViewController = rvc;
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissWindow)];
[window addGestureRecognizer:tap];

}
-(void)dismissWindow{
window.hidden = YES;
window = nil;
}


keyWindow

keyWindow是获取键盘和其他非触摸事件的window,同一时间只能有一个window为keywindow。所以,如果自己创建的Window要相应除触摸外的事件,要设置为keyWindow
The key window is the one that is designated to receive keyboard and other non-touch related events. Only one window at a time may be the key window.


makeKeyWindow //设置当前window为main window.


keyWindow的”生命周期”

这两个方法类似于viewWillAppear等,自动触发,不要手动调用。

- becomeKeyWindow
- resignKeyWindow
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios sdk UIWindow