手工创建UIWindow,可以在应用开发中将某些界面覆盖到最上层
/* eg.支付宝客户端的手势解锁功能\ 密码保护输入界面\ 应用的启动介绍页\ 应用内的通知提醒显示\ 应用内的弹框广告等
// 如果我们创建的 UIWindow 需要处理键盘事件,那就需要将其合理的设置为 keyWindow. keyWindow是被系统设计用来接收键盘和其他非触摸事件的 UIWindow.我们可以通过makeKeyWindow 和 resignKeyWindow来将自己创建的UIWindow 设置成keyWindow.但不要滥用
示例代码: 实现一个继承自 UIWindow 的子类 PasswordInputWindow ,完成密码输入界面的显示和处理逻辑..
// 只需应用进入后台的回调函数调用即可
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[PasswordInputWindow sharedInstance] show];
}
#import
@interface PasswordInputWindow : UIWindow
+ (PasswordInputWindow *)sharedInstance;
- (void)show;
@end
#import "PasswordInputWindow.h"
@implementation PasswordInputWindow
{
UITextField * _textField;
}
+ (PasswordInputWindow *)sharedInstance{
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] initWithFrame:[UIScreen mainScreen].bounds];
});
return sharedInstance;
}
- (void)show{
[self makeKeyWindow];// 如果我们创建的 UIWindow 需要处理键盘事件,那就需要将其合理的设置为 keyWindow. keyWindow是被系统设计用来接收键盘和其他非触摸事件的 UIWindow.我们可以通过makeKeyWindow 和 resignKeyWindow来将自己创建的UIWindow 设置成keyWindow.但不要滥用
self.hidden = NO;
}
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 200, 20)];
label.text = @"清输入密码";
[self addSubview:label];
UITextField * textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 80, 200, 20)];
textField.backgroundColor = [UIColor whiteColor];
textField.secureTextEntry = YES;
[self addSubview:textField];
UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(10, 110, 200, 44)];
[button setBackgroundColor:[UIColor blueColor]];
button.titleLabel.textColor = [UIColor whiteColor];
[button setTitle:@"确定" forState: UIControlStateNormal];
[button addTarget:self action:@selector(completeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
self.backgroundColor = [UIColor lightGrayColor];
_textField = textField;
}
return self;
}
- (void)completeButtonClicked:(id)sender{
if ([_textField.text isEqualToString:@"abcd"]) {
[_textField resignFirstResponder];
[self resignKeyWindow];
self.hidden = YES;
}else{
[self showErrorAlertView];
}
}
- (void)showErrorAlertView{
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"密码错误" delegate: self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
}
@end