Swift 新手,以及使用 React Native 处理原生 iOS 代码的新手。我正在尝试使用常见的
UITextField
方法来阻止某些屏幕上的屏幕截图。我这里有一个函数initTextField
:
private var secureTextField: UITextField?
private func initTextField() {
let boundLength = max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
secureTextField = UITextField(frame: CGRect(x: 0, y: 0, width: boundLength, height: boundLength))
secureTextField!.isSecureTextEntry = true
secureTextField!.isUserInteractionEnabled = false
secureTextField!.backgroundColor = .red
if let rootView = UIApplication.shared.keyWindow?.rootViewController?.view {
for subview in rootView.subviews {
subview.addSubview(secureTextField!)
subview.layer.superlayer?.addSublayer(secureTextField!.layer)
secureTextField!.layer.sublayers?.last?.addSublayer(subview.layer)
}
}
}
这有效。屏幕截图变成红色,并且在应用程序切换器上该应用程序也是红色的。我最终不得不使用这个定义
rootView
,不确定是否是因为我正在使用 React Native,但无论如何,它是有效的。
在某些屏幕上,我想禁用此功能并允许屏幕截图,但尚未弄清楚如何执行此操作。如何撤消/删除所有子图层/子视图上的
UITextField
?
谢谢!
要删除与
UITextField
关联的图层,您需要从其超级视图中删除 UITextField
,这将自动将其图层从视图层次结构中分离。如果由于某种原因仍然需要单独操作图层,可以直接从其超级图层中删除该图层。具体方法如下:
UITextField
及其层您可以扩展
removeTextField()
方法以确保该图层也从视图层次结构中删除:
/// Removes the secure text field and its layer, enabling screenshots.
private func removeTextField() {
guard let textField = secureTextField else { return }
// Remove the text field from its superview
textField.removeFromSuperview()
// Additionally, remove the text field's layer from its superlayer if needed
textField.layer.removeFromSuperlayer()
// Clean up the reference
secureTextField = nil
}
textField.removeFromSuperview()
:这会将 UITextField
从其父视图中分离出来,这也会有效地从视图层次结构中删除相应的层。textField.layer.removeFromSuperlayer()
:这条线确保层本身与其超级层分离(如果它仍然附着)。如果您已经从视图层次结构中删除了 UITextField
,则通常不需要此步骤,但可以添加它作为预防措施。secureTextField = nil
:清除对UITextField
的引用以防止内存泄漏。如果您之前已手动将
UITextField
的图层添加到其他视图或图层,则需要迭代这些视图或图层以从每个视图或图层中删除文本字段的图层。具体方法如下:
/// Removes the secure text field's layer from all superlayers where it might have been added.
private func removeTextFieldLayerFromAllSuperlayers() {
guard let textField = secureTextField else { return }
// Iterate over all superlayers to remove the layer
if let superlayers = textField.layer.sublayers {
for sublayer in superlayers {
sublayer.removeFromSuperlayer()
}
}
// Now remove the text field itself
textField.removeFromSuperview()
secureTextField = nil
}
UITextField
的图层添加到多个子图层(例如,使用 addSublayer()
),那么您可能需要显式删除这些图层。此代码可确保彻底清理视图和图层,从而允许您安全地切换屏幕截图阻止功能。