iOS 12 : UITextField not deallocating

标签 ios uitextfield ios12

UITextField 预先填充了一些文本并且键盘处于事件状态,关闭 Controller 时不会取消分配。这是一个例子:

class TextFieldViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.lightGray
        let textField = TestTextField()
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.backgroundColor = UIColor.red
        textField.text = "Text"//commment this line and deinit will be called

        view.addSubview(textField)
        textField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        textField.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        textField.widthAnchor.constraint(equalToConstant: 200).isActive = true
        textField.heightAnchor.constraint(equalToConstant: 50).isActive = true
    }

    deinit {
        print("Deinit controller")
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        (view.subviews.first as? UITextField)?.becomeFirstResponder()
    }}

}

class TestTextField: UITextField {

    deinit {
        print("never gets called")
    }

}

呈现 Controller 的代码:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
            self?.present(TextFieldViewController(), animated: true, completion: nil)
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
                self?.dismiss(animated: true, completion: nil)
            }
        }
    }

}
TextFieldViewController

deinit 被调用,但 TestTextField 的 deinit 未被调用。关闭 Controller 后,文本字段保留在内存图中:

enter image description here

有趣的点:

  • textField.text = "Text" 注释此行并删除文本的 deinit 字段将被调用。即使您从键盘输入文本。
  • 保留textField.text = "Text" 取消注释,但注释viewDidAppear 方法(即不打开键盘)和文本字段的 deinit 将是 打电话。
  • 问题是似乎仅在 ios 12.1+ 上存在

最佳答案

嗯...这看起来确实像一个错误。

快速测试表明,如果在成为响应者之前分配了文本字段的 .text 属性,则会出现此问题,但如果您随后进行分配,则不会出现此问题.

所以,如果您正在寻找“解决方法”,您可以这样做......

按照您的指示注释掉 viewDidLoad() 中的行:

//textField.text = "Text"//commment this line and deinit will be called

然后在 .becomeFirstResponder() 之后添加一行:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    (view.subviews.first as? UITextField)?.becomeFirstResponder()
    (view.subviews.first as? UITextField)?.text = "Text"
}

您将“看到”正在添加的文本,因为当 View 向上滑动时,文本字段将为空。因此,它可能适合也可能不适合。

关于iOS 12 : UITextField not deallocating,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55533362/

相关文章:

iOS 约束 - 中心图像和动态文本

html - Bootstrap 子菜单插入符在 iPad 3 上不可见

ios - 如何在 UITextField 中为每 3 位数字添加逗号?

iOS 12 IAP 沙盒

ios - 在 iOS 12 中,UICollectionView 布局单元格何时在 nib 中使用自动布局

ios - 将设备升级到 iOS12 后应用程序崩溃

ios - iOS 本地化问题 - NSLocalizedString

ios - 用手指 move UIView

ios - 左右对齐 UITextView。

ios - 点击 UITextField 在 UITableView 中显示数据