现有的APP中有许多涉及到隐私信息的页面,在被截图后会出现“保护个人隐私”等字样的提示,我们也可做其他操作,现在我们来进行阐述。
一、截屏活动的获取
iOS中通过此方法对截图活动进行检测,一旦捕获到就执行你所选定的方法。takeScreenshotAction为自己定义的方法。
OC:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(takeScreenshotAction) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
- (void)takeScreenshotAction {
NSLog(@"截屏");
}
Swift:
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.takeScreenshotAction), name: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object:nil)
二、拓展
截屏后,弹出请保护个人隐私的弹窗,一定时间后消失
方法一:添加动画,使label在指定时间内消失
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
label.center = self.view.center;
label.backgroundColor = [UIColor grayColor];
label.text = @"请注意保护个人隐私";
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:label];
[UIView animateWithDuration:0.2 //动画时间
delay:2.0 //开始延迟时间
options:UIViewAnimationOptionCurveEaseInOut //弹入弹出
animations:^{
label.alpha = 0;
} completion:^(BOOL finished) {
label.hidden = YES;
}];
方法二:使用[self performSelector:<#(nonnull SEL)#> withObject:<#(nullable id)#> afterDelay:<#(NSTimeInterval)#>],到达指定时间,使其消失。为增加其美观性可以为其添加动画。
[self performSelector:@selector(hide) withObject:nil afterDelay:2.0];
- (void)hide {
for (UIView *view in self.view.subviews) {
if ([view isKindOfClass:UILabel.class]) {
// [UIView animateWithDuration:0.2 //动画时间
// delay:0 //开始延迟时间
// options:UIViewAnimationOptionCurveEaseInOut //弹入弹出
// animations:^{
// view.alpha = 0;
// } completion:^(BOOL finished) {
// view.hidden = YES;
// }];
view.hidden = YES;
}
}
}
三、主要代码
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(takeScreenshotAction) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}
- (void)takeScreenshotAction {
NSLog(@"截屏");
[self initUI];
}
- (void)initUI {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
label.center = self.view.center;
label.backgroundColor = [UIColor grayColor];
label.text = @"请注意保护个人隐私";
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:label];
// [self performSelector:@selector(hide) withObject:nil afterDelay:2.0];
[UIView animateWithDuration:0.2 //动画时间
delay:2.0 //开始延迟时间
options:UIViewAnimationOptionCurveEaseInOut //弹入弹出
animations:^{
label.alpha = 0;
} completion:^(BOOL finished) {
label.hidden = YES;
}];
}
- (void)hide {
for (UIView *view in self.view.subviews) {
if ([view isKindOfClass:UILabel.class]) {
// [UIView animateWithDuration:0.2 //动画时间
// delay:0 //开始延迟时间
// options:UIViewAnimationOptionCurveEaseInOut //弹入弹出
// animations:^{
// view.alpha = 0;
// } completion:^(BOOL finished) {
// view.hidden = YES;
// }];
view.hidden = YES;
}
}
}