密码保护功能

Posted by Genie on April 25, 2020
  • PasswordInputWindow.h
1
2
3
4
5
6
7
8
9
10
#import <UIKit/UIKit.h>

@interface PasswordInputWindow : UIWindow

+ (PasswordInputWindow *)sharedInstance;

- (void)show;

@end

  • PasswordInputWindow.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#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
{
    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, 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 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];
    self.hidden = NO;
}

- (void)completeButtonPressed:(id)sender {
    if ([_textField.text isEqualToString:@"abcd"]) {
        [_textField resignFirstResponder];
        # [self resignKeyWindow];
        self.hidden = YES;
        self = nil;
    	 [self makeKeyWindow];
    } else {
        [self showErrorAlertView];
    }
}

- (void)showErrorAlertView {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"密码错误,正确密码是abcd"
                                                       delegate:nil cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil, nil];
    [alertView show];
}

@end

在 AppDelegate Lifecycle 中 ` applicationDidBecomeActive`

call ` [[PasswordInputWindow sharedInstance] show]; `