Skip to content

Instantly share code, notes, and snippets.

@nonisolated
Last active July 7, 2023 14:59
Show Gist options
  • Select an option

  • Save nonisolated/b0e9162bed083da61d9fc86253c40ea6 to your computer and use it in GitHub Desktop.

Select an option

Save nonisolated/b0e9162bed083da61d9fc86253c40ea6 to your computer and use it in GitHub Desktop.
A SwiftUI wrapper for UIView that provides protection against screenshots. This view uses a UITextField with isSecureTextEntry set to true to create an invisible, screenshot-proof container in which you can place other views.
public struct SecureView<Content: View>: UIViewRepresentable {
let content: () -> Content
public init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
public func makeUIView(context: Context) -> UIView {
let secureTextField = UITextField()
secureTextField.isSecureTextEntry = true
secureTextField.isUserInteractionEnabled = false
guard let secureView = secureTextField.layer.sublayers?.first?.delegate as? UIView else {
return UIView()
}
secureView.subviews.forEach { subview in
subview.removeFromSuperview()
}
let contentHostingController = UIHostingController(rootView: content())
contentHostingController.view.backgroundColor = .clear
contentHostingController.view.translatesAutoresizingMaskIntoConstraints = false
secureView.addSubview(contentHostingController.view)
NSLayoutConstraint.activate([
contentHostingController.view.topAnchor.constraint(equalTo: secureView.topAnchor),
contentHostingController.view.bottomAnchor.constraint(equalTo: secureView.bottomAnchor),
contentHostingController.view.leadingAnchor.constraint(equalTo: secureView.leadingAnchor),
contentHostingController.view.trailingAnchor.constraint(equalTo: secureView.trailingAnchor)
])
return secureView
}
public func updateUIView(_ uiView: UIView, context: Context) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment