本文参考:唐巧的《iOS进阶》
一、UIWindow简介
在 iOS 应用中,我们使用 UIWindow 和 UIView 来呈现界面。UIWindow 并不包含任何默认 的内容,但是它被当作 UIView 的容器,用于放置应用中所有的 UIView。
二、是不是只要是新创建的 UIWindow 一定就会覆盖在界面的最上面呢?
UIWindow 有一个类型为“UIWindowLevel”的属性,该属性定义了 UIWindow 的层级,系 统定义的 WindowLevel 一共有 3 种取值,如下所示:
①UIKIT_EXTERN const UIWindowLevel UIWindowLevelNormal;
②UIKIT_EXTERN const UIWindowLevel UIWindowLevelAlert;
③UIKIT_EXTERN const UIWindowLevel UIWindowLevelStatusBar;
我们通过如下代码将这些值输出:
NSLog(@”UIWindowLevelNormal=%f␣UIWindowLevelStatusBar=%f␣UIWindowLevelAlert=%f”, UIWindowLevelNormal, UIWindowLevelStatusBar, UIWindowLevelAlert);
最终得到的结果是:(在实际中,WindowLevel 的取值并不限于下面输出的值。)
UIWindowLevelNormal=0.000000
UIWindowLevelStatusBar=1000.000000
UIWindowLevelAlert=2000.000000
三、UIWindow的一个小应用
当程序从后台重新回来,跳出一个密码输入界面。密码输入正确才能继续操作
#import "PasswordWindow.h"
@implementation PasswordWindow {
UITextField *_textField;
}
+ (PasswordWindow *)sharedInstance
{
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] initWithFrame:[UIScreen mainScreen].bounds];
});
return sharedInstance;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 200, 20)];
label.text = @"请输入密码";
[self addSubview:label];
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 80, 200, 30)];
textField.backgroundColor = [UIColor whiteColor];
textField.secureTextEntry = YES;
[self addSubview:textField];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 110, 200, 44)];
[button setBackgroundColor:[UIColor blackColor]];
button.titleLabel.textColor = [UIColor blackColor];
[button setTitle:@"确定" forState:UIControlStateNormal];
[button addTarget:self action:@selector(completeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
self.backgroundColor = [UIColor yellowColor];
_textField = textField;
}
return self;
}
- (void)completeButtonPressed:(UIButton *)sender
{
if ([_textField.text isEqualToString:@"abcd"]) {
//因为我们处理的UIWindow需要处理键盘事件,所以需要把它设置为keyWindow
[_textField resignFirstResponder];
[self resignKeyWindow];
self.hidden = YES;
}
else
{
[self showErrorAlertView];
}
}
- (void)showErrorAlertView
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"密码错误" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
}
- (void)show
{
[self makeKeyWindow];
self.hidden = NO;
}
@end
//AppDelegate.m文件
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[PasswordWindow sharedInstance] show];
}