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