How to prevent screenshot for UIView in iOS?

iOS – Apple provides screenshot detection notification but not providing direct solution for prevention.

Here I found solution for preventing screenshot taking from the UIView. It’s a simple extension of the UIView that allows to hide it from screen-capturing and also from screen recording. The solution uses ability of UITextField to hide a password from capturing.

extension UIView {
func preventScreenshot() {
DispatchQueue.main.async {
let field = UITextField()
field.isSecureTextEntry = true
self.addSubview(field)
field.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
field.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.layer.superlayer?.addSublayer(field.layer)
field.layer.sublayers?.first?.addSublayer(self.layer)
}
}
}

Usage:

viewSecure.preventScreenshot()

So, when you take screenshot the logic of text field secure entry (password text field) will not allow to take screenshot of that part.

ScrollView Screenshot Prevention

Update: Here is recursive function for preventing screenshot.

extension UIView {
func preventScrollViewScreenshotRecursive() {
guard superview != nil else {
for subview in subviews {
subview.preventScrollViewScreenshotRecursive()
}
return
}
let guardTextField = UITextField()
guardTextField.backgroundColor = .red
guardTextField.translatesAutoresizingMaskIntoConstraints = false
guardTextField.tag = Int.max
guardTextField.isSecureTextEntry = true
addSubview(guardTextField)
guardTextField.isUserInteractionEnabled = false
sendSubviewToBack(guardTextField)
layer.superlayer?.addSublayer(guardTextField.layer)
guardTextField.layer.sublayers?.first?.addSublayer(layer)
guardTextField.centerYAnchor.constraint(
equalTo: self.centerYAnchor
).isActive = true
guardTextField.centerXAnchor.constraint(
equalTo: self.centerXAnchor
).isActive = true
}
}

Support

If you like then Buy me a coffee ☕️

Conclusion

Let me know if you have any questions, comments, or feedback – contact me on Twitter.

Stay Safe At Home. Learn Something New. Share To The World.
Happy Coding 🙂

Did you know? How to hide keyboard in SwiftUI?

iOS 15 have new property wrapper: @FocusState. This is exactly like a regular @State property, except it’s specifically designed to handle input focus in our UI.

In this tutorial we will get to know that how to hide keyboard or you can say how to work with the @FocusState in SwiftUI.

Read more

What’s new in Xcode 13.3?

Xcode 13.3 includes SDKs for iOS 15.4, iPadOS 15.4, tvOS 15.4, watchOS 8.5, and macOS Monterey 12.3. Xcode 13.3 requires a Mac running macOS Monterey 12 or later.

Build System

The build system and Swift compiler have a new mode that better utilizes available cores, resulting in faster builds for Swift projects. The mode is opt-in, and you can enable it globally with the following user default:

Read more