仿照支付客户端退出后台再次打开需要手势解锁

2018-04-26  本文已影响19人  潮人花钱不用钱

先看下效果图(布局就随便看看吧 ,重点是效果😂)


finished3.gif

需求:上面的效果图是在用户从应用程序的界面按下Home键退出,过一段时间再从后台切换回来的时候,显示一个密码输入的界面,只有当用户输入了正确的密码才能进入退出前的界面.
需求分析:因为这个密码输入界面可能从任何应用界面弹出,并且需要盖在所有的界面上,所有它适合用一个UIWindow来实现.代码如下

1.创建一个PasswordInputWindow类继承自UIWindow,在.h文件中实现两个方法

@interface PasswordInputWindow : UIWindow

+(PasswordInputWindow *)sharedInstance;
- (void)show;

@end

2.在PasswordInputWindow类的.m文件中实现对应的方法

+(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(compleBtnPressed) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        self.backgroundColor = [UIColor yellowColor];
        self.textField = textField;
    }
    return self;
}
- (void)show{
    [self makeKeyWindow];
    self.hidden = NO;
}
- (void)compleBtnPressed{
    if ([self.textField.text isEqualToString:@"abcd"]) {
        [self.textField resignFirstResponder];
        [self resignKeyWindow];
        self.hidden = YES;
    }else{
        [self showErrorAlterView];
    }
}
- (void)showErrorAlterView{
    UIAlertView * view = [[UIAlertView alloc]initWithTitle:nil message:@"密码错误" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
    [view show];
}

3.我们只需要在应用进入后台的回调函数中,把自己的显示出来即可.

//进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[PasswordInputWindow sharedInstance]show];
}

总结:支付宝客户端的手势解锁功能,应用的启动介绍页,应用内的弹窗广告等都是利用的UIWindow一个很好的应用.
参考资料:ios开发进阶(唐巧)

上一篇下一篇

猜你喜欢

热点阅读