用户从任何一个界面按home键退出,再过一段时间从后台切回来,显示一个输入密码界面,只有用户输入正确的密码,才能进入推出前的界面,我们用一个集成自UIWindow的子类PasswordInputWindow,完成界面显示和逻辑;
@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;
}
-(id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 200, 20)];
label.text = @"请输入密码";
label.backgroundColor = [UIColor redColor];
[self addSubview:label];
UITextField * textField = [[UITextField alloc] initWithFrame: CGRectMake(10, 80, 200, 20)];
textField.backgroundColor = [UIColor whiteColor];
textField.placeholder = @"请输入密码";
textField.secureTextEntry = YES;//密码输入
textField.clearButtonMode = UITextFieldViewModeAlways; //输入框中是否有个叉号,在什么时候显示,用于一次性删
textField.clearsOnBeginEditing = YES; //再次编辑就清空
[self addSubview:textField];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 110, 200, 44)];
[button setBackgroundColor:[UIColor blueColor]];
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)show {
[self makeKeyWindow];//设置成KeyWindow,接受键盘和其他非触摸控件
self.hidden = NO;
}
-(void)completeButtonPressed:(id)sender {
if ([_textField.text isEqualToString:@"abcd"]) {
[_textField resignFirstResponder] ;//键盘消失,取消第一响应者;
[self resignKeyWindow];//设置成KeyWindow
self.hidden = YES;
_textField.text = nil;
}else {
[self showErrorAlertView];
}
}
-(void)showErrorAlertView {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"密码错误,正确密码是abcd" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
}
@end
只需要在应用进入后台的回调函数中,将该UIWindow显示出来即可
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[PasswordInputWindow sharedInstance]show];
}