IOS 防截屏实现

.h文件

objectivec 复制代码
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface HSNoScreenShotView : UIView

@end

NS_ASSUME_NONNULL_END

.m文件

objectivec 复制代码
#import "HSNoScreenShotView.h"

@interface HSNoScreenShotView ()

@property (nonatomic,strong) UITextField *textField;
@property (nonatomic,strong) UIView *clearView;

@end

@implementation HSNoScreenShotView

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.textField.frame = self.bounds;
    self.clearView.frame = self.bounds;

    if (self.textField.superview != self) {
        [self addSubview:self.textField];
    }
}

- (void)setupUI {
    [self addSubview:self.textField];
    self.textField.subviews.firstObject.userInteractionEnabled = YES;
    [self.textField.subviews.firstObject addSubview:self.clearView];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}


- (void)keyboardWillShow:(NSNotification *)noti {
    if (self.textField.isFirstResponder) {
        [self.textField resignFirstResponder];
        self.textField.subviews.firstObject.userInteractionEnabled = YES;
    }
}

- (void)addSubview:(UIView *)view {
    [super addSubview:view];
    if (self.textField != view) {
        [self.clearView addSubview:view];
    }
}

- (UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] init];
        _textField.secureTextEntry = YES;
    }
    return _textField;
}

- (UIView *)clearView {
    if (!_clearView) {
        _clearView = [[UIView alloc] init];
        _clearView.backgroundColor = [UIColor clearColor];
    }
    return _clearView;
}

@end

使用逻辑,在你项目实现上面的防截图视图。将你不想被截图的视图添加为HSNoScreenShotView的子视图就行。

相关推荐
杂雾无尘1 小时前
Swift 5.9 新特性揭秘:非复制类型的安全与高效
ios·swift·apple
Thomas_YXQ4 小时前
Unity3D iOS闪退问题解决方案
ios
Daniel_Coder7 小时前
iOS Widget 开发-7:TimelineProvider 机制全解析:构建未来时间线
ios·swift·widget
Daniel_Coder8 小时前
iOS Widget 开发-3:Widget 的种类与尺寸(主屏、锁屏、灵动岛)
ios·swift·widget
Engandend1 天前
Flutter与iOS混合开发交互
flutter·ios·程序员
山水域1 天前
GoogleAdsOnDeviceConversion 库的作用与用法
ios
Lucifer晓1 天前
记录一次Flutter项目上传App Store Connect出现“Validation failed”错误的问题
flutter·ios
阿里超级工程师1 天前
经验分享-没有xcode也可以上传App Store Connect
xcode·上传ipa
扶我起来还能学_1 天前
uniapp Android&iOS 定位权限检查
android·javascript·ios·前端框架·uni-app
杂雾无尘1 天前
SwiftUI 新手必读:如何用纯 SwiftUI 在应用中实现分段控制?
ios·swift·apple