首页 > 解决方案 > iOS 12:UITextField 未解除分配

问题描述

UITextField预先填充了一些文本并且键盘处于活动状态时关闭控制器时不会解除分配。这是一个例子:

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")
    }

}

呈现控制器的代码:

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)
            }
        }
    }

}

deinitofTextFieldViewController被调用但 deinit ofTestTextField不是。关闭控制器后,文本字段保留在内存图中:

在此处输入图像描述

有趣的点:

标签: iosuitextfieldios12

解决方案


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

快速测试表明,如果.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"
}

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


推荐阅读