iOS 继承 UIWindow 的密码保护功能

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[PasswordInPutWindow shareHandle] show];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

#import "PasswordInPutWindow.h"

@interface PasswordInPutWindow ()

@end

@implementation PasswordInPutWindow {
    UITextField *_textField;
}

+ (PasswordInPutWindow *)shareHandle{
    static PasswordInPutWindow *passwordInPut = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        passwordInPut = [[PasswordInPutWindow alloc] init];
    });
    return passwordInPut;
}
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 20, 200, 20)];
        label.text = @"请输入密码";
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor whiteColor];
        [self addSubview:label];
        
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 60, 200, 20)];
        _textField.placeholder = @"请输入密码验证";
        _textField.backgroundColor = [UIColor whiteColor];
        [self addSubview:_textField];
        
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake(50, 100, 200, 20);
        button.backgroundColor = [UIColor whiteColor];
        [button setTitle:@"确认" forState:(UIControlStateNormal)];
        [button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        [self addSubview:button];
    }
    return self;
}
- (void)buttonClick:(UIButton *)button{
    if ([_textField.text isEqualToString:@"登陆时候的密码"]) {
        [self resignKeyWindow];
        [self setHidden:YES];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                            message:@"密码输入错误!"
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil, nil];
        alertView.backgroundColor = [UIColor whiteColor];
        [alertView show];
    }
}
- (void)show{
    [self makeKeyWindow];
    [self setHidden:NO];
}

你可能感兴趣的:(iOS 继承 UIWindow 的密码保护功能)