iOS学习—禁止截屏/截屏隐藏指定内容

一、前言

        手机截屏是手机系统操作,app是无法阻止这个操作的。为了防止app内容被截屏我们可以通过UITextfeild控件的secureTextEntry属性来实现截屏空白页面,其原理就是利用了开启安全文本输入属性,将需要隐藏的内容添加到UITextfeild的子视图(textField.subviews.firstObject)上,就可以达到此效果。但是此方法只能iOS13以上使用。

二、代码实现

        想要隐藏截图,首先要创建一个UITextField,并将secureTextEntry属性设置为Yes。

    UITextField *textField = [[UITextField alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:textField];
    textField.backgroundColor = [UIColor whiteColor];
    textField.secureTextEntry = YES;

        为了体现效果,我使用UILabel画了一个label,来看效果。左边是未使用secureTextEntry,右边是使用了secureTextEntry。

    UITextField *textField = [[UITextField alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:textField];
    textField.backgroundColor = [UIColor whiteColor];
    textField.secureTextEntry = YES;
    
    UILabel *label = [UILabel new];
    label.frame = CGRectMake(0, 0, 200, 100);
    label.center = self.view.center;
    label.layer.masksToBounds = YES;
    label.layer.cornerRadius = 50;
    label.backgroundColor = [UIColor orangeColor];
    label.text = @"This is a label";
    label.font = [UIFont systemFontOfSize:25];
    label.textAlignment = NSTextAlignmentCenter;
    //将想要隐藏的内容添加到UITextField的子视图上
    [textField.subviews.firstObject addSubview:label];
iOS学习—禁止截屏/截屏隐藏指定内容_第1张图片 截图未隐藏 iOS学习—禁止截屏/截屏隐藏指定内容_第2张图片 截图隐藏

         但是你会发现还有一个问题,点击屏幕可以输入文字。

iOS学习—禁止截屏/截屏隐藏指定内容_第3张图片

        这显然不符合我们的需求,这时候我们就需要用到UITextField代理(textFieldShouldBeginEditing)来限制输入,在主代码段加入textField.delegate = self;

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return NO;
}

三、具体代码

#import "ViewController.h"

@interface ViewController () 

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UITextField *textField = [[UITextField alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:textField];
    textField.backgroundColor = [UIColor whiteColor];
    textField.secureTextEntry = YES;
    textField.delegate = self;
    
    UILabel *label = [UILabel new];
    label.frame = CGRectMake(0, 0, 200, 100);
    label.center = self.view.center;
    label.layer.masksToBounds = YES;
    label.layer.cornerRadius = 50;
    label.backgroundColor = [UIColor orangeColor];
    label.text = @"This is a label";
    label.font = [UIFont systemFontOfSize:25];
    label.textAlignment = NSTextAlignmentCenter;
    //将想要隐藏的内容添加到UITextField的子视图上
    [textField.subviews.firstObject addSubview:label];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return NO;
}

 

你可能感兴趣的:(iOS,学习,ios,xcode,objective-c,ui)