无法从子图层中删除 UITextField

问题描述 投票:0回答:1

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

谢谢!

ios swift objective-c react-native
1个回答
0
投票

要删除与

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
}

说明

  1. textField.removeFromSuperview()
    :这会将
    UITextField
    从其父视图中分离出来,这也会有效地从视图层次结构中删除相应的层。
  2. textField.layer.removeFromSuperlayer()
    :这条线确保层本身与其超级层分离(如果它仍然附着)。如果您已经从视图层次结构中删除了
    UITextField
    ,则通常不需要此步骤,但可以添加它作为预防措施。
  3. 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()
    ),那么您可能需要显式删除这些图层。

此代码可确保彻底清理视图和图层,从而允许您安全地切换屏幕截图阻止功能。

© www.soinside.com 2019 - 2024. All rights reserved.