iOS 12:UITextField没有解除分配

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

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

}

deinitTextFieldViewController被召唤但TestTextField的deinit不是。关闭控制器后,文本字段保留在内存图中:

enter image description here

有趣的点:

  • textField.text = "Text"评论此行和文本字段的deinit将被调用。即使您从键盘输入文本。
  • keeptextField.text = "Text"取消注释但注释viewDidAppear方法(即不要打开键盘)和文本字段的deinit将被调用。
  • 问题似乎只出现在ios 12.1+上
ios uitextfield ios12
1个回答
0
投票

嗯......这看起来像个bug。

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

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

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