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 后,文本字段保留在内存图中:
有趣的点:
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/