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

小计UIWindow

2016-03-30 17:20 435 查看
每一个iOS程序都有一个UIWindow,在我们通过模板简历工程的时候,xcode会自动帮我们生成一个window,然后让它变成keyWindow并显示出来。这一切都来的那么自然,以至于我们大部分时候都忽略了自己也是可以创建UIWindow对象。

  通常在我们需要自定义UIAlertView的时候(IOS 5.0以前AlertView的背景样式等都不能换)我们可以使用UIWindow来实现(设置windowLevel为Alert级别),网上有很多例子,这里就不详细说了。

一、UIWindowLevel

  我们都知道UIWindow有三个层级,分别是Normal,StatusBar,Alert。打印输出他们三个这三个层级的值我们发现从左到右依次是0,1000,2000,也就是说Normal级别是最低的,StatusBar处于中等水平,Alert级别最高。而通常我们的程序的界面都是处于Normal这个级别上的,系统顶部的状态栏应该是处于StatusBar级别,UIActionSheet和UIAlertView这些通常都是用来中断正常流程,提醒用户等操作,因此位于Alert级别。

  上一篇文章中我也提到了一个猜想,既然三个级别的值之间相差1000,而且我们细心的话查看UIWindow的头文件就会发现有一个实例变量_windowSublevel,那我们就可以定义很多中间级别的Window。例如可以自定义比系统UIAlertView级别低一点儿的window。于是写了一个小demo,通过打印发现系统的UIAlertView的级别是1996,而与此同时UIActionSheet的级别是2001,这样也验证了subLevel的确存在。

二、自建UIWindow

UIStatusbar 、 UIAlertView 、UIActionSheet 还有键盘,都属于UIWindow类。

在 我们 希望 做点什么事的时候会 自建 UIWindow, 譬如说 : 我想做一个 置顶的Button,不会被覆盖 这种,那就要用到自建UIWindow了。代码示例:

@interface ViewController ()
@property(strong,nonatomic)UIWindow *window;
@property(strong,nonatomic)UIButton *button;
@end

@implementation ViewController

- (void)viewDidLoad
{
}

-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[self creatBtn];//自建window,不能放在viewDidLoad中

}

-(void)creatBtn{
_button = [UIButton buttonWithType:UIButtonTypeCustom];
_button.showsTouchWhenHighlighted = YES;
[_button setTitle:@"悬浮按钮" forState:UIControlStateNormal];
[_button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[_button setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
_button.frame = CGRectMake(0, 0, 80, 80);
[_button addTarget:self action:@selector(btnChick) forControlEvents:UIControlEventTouchUpInside];
_window = [[UIWindow alloc]initWithFrame:CGRectMake(100, 200, 80, 80)];
_window.windowLevel = UIWindowLevelAlert+1;//设置成最高等级
_window.backgroundColor = [UIColor yellowColor];
_window.hidden = NO;
_window.layer.cornerRadius = 40;
_window.layer.masksToBounds = YES;
[_window addSubview:_button];
[[[UIApplication sharedApplication].delegate window] resignKeyWindow];
[_window makeKeyAndVisible];
}

-(void)btnChick{
ViewController * vc = [[ViewController alloc]init] ;
vc.abc = YES;
vc.view.backgroundColor = [UIColor blueColor];
[self presentViewController:vc  animated:YES completion:nil];
}
@end


我在 ViewDidLoad 中自建 window 会报错,但是如果 延时自建 就不会报错,我猜测是 刚生成Window View 还没有显示 就 把新的 makeKeyandValue 会冲突,所以放到ViewDidLoad 中就没事了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: