越来越多App开始注重对于信息的保护,如支付宝、掌上生活等App在退到后台(回到桌面或者切换App),会加上一个保护层,如下图支付宝的界面:
支付宝保护界面
这个其实很简单,我们只需要在AppDelegate的applicationDidEnterBackground方法中添加一个保护界面,在applicationDidBecomeActive方法中把这个保护界面移除掉就,就初步实现了保护的效果。
初步封装了一个类来实现,代码如下:
JQBackgroundSafeView.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface JQBackgroundSafeView : UIView
/**
请在 AppDelegate 中的 didFinishLaunchingWithOptions调用
*/
+ (void)initSafeView;
/**
请在 AppDelegate 中的 applicationDidEnterBackground调用
*/
+ (void)addSafeView;
/**
请在 AppDelegate 中的 applicationDidBecomeActive调用
*/
+ (void)removeSafeView;
@end
NS_ASSUME_NONNULL_END
JQBackgroundSafeView.m
#import "JQBackgroundSafeView.h"
@interface JQBackgroundSafeView ()
@property (nonatomic,assign) BOOL isFinishLaunching;
@property (nonatomic,strong) UIView *safeView;
@end
@implementation JQBackgroundSafeView
+ (instancetype)shareInstance
{
static JQBackgroundSafeView *_mySingle = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_mySingle = [[JQBackgroundSafeView alloc] initWithFrame:UIScreen.mainScreen.bounds];
[_mySingle setBackgroundColor:[UIColor clearColor]];
UIBlurEffect *blurEffect =[UIBlurEffect effectWithStyle:UIBlurEffectStyleRegular];
UIVisualEffectView *effectView =[[UIVisualEffectView alloc]initWithEffect:blurEffect];
effectView.frame = UIScreen.mainScreen.bounds;
[_mySingle addSubview:effectView];
});
return _mySingle;
}
+ (void)initSafeView {
[JQBackgroundSafeView shareInstance].isFinishLaunching = YES;
}
+ (void)addSafeView {
if (![JQBackgroundSafeView shareInstance].isFinishLaunching) {
[[[UIApplication sharedApplication] keyWindow] addSubview:[JQBackgroundSafeView shareInstance]];
}
}
+ (void)removeSafeView {
[JQBackgroundSafeView shareInstance].isFinishLaunching = NO;
[[JQBackgroundSafeView shareInstance] removeFromSuperview];
}
@end
实现的话,如JQBackgroundSafeView.h的注释写的那样,只要在AppDalegate中调用JQBackgroundSafeView的类方法即可:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[JQBackgroundSafeView initSafeView];
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
[JQBackgroundSafeView addSafeView];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[JQBackgroundSafeView removeSafeView];
}
这里只是实现了一个毛玻璃效果保护页,如果想要实现其他效果的话就稍微修改下即可。
网友评论