ios - 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)
}
}
}
}
deinit
ofTextFieldViewController
被调用但 deinit ofTestTextField
不是。关闭控制器后,文本字段保留在内存图中:
有趣的点:
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"
}
您将“看到”正在添加的文本,因为当视图向上滑动时,文本字段将为空。所以,它可能合适,也可能不合适。
推荐阅读
- amazon-web-services - 如何为两个不同的 API 使用 apigateway 授权方
- python - Python 关键字与 xml 标签相同
- java - 无法调用“org.apache.poi.ss.usermodel.Cell.getStringCellValue()”,因为 org.apache.poi.ss.usermodel.Row.getCell(int) 的返回值为 null
- r - 如何在 R 中选择性地为直方图条着色?
- javascript - 无法获得多个前缀来使用 discord.js。我怎样才能重写它以便它识别两个前缀?
- angular - Angular 将变量绑定到具有字符串类型值的哈希图
- python - Python 文件错误:解包需要 16 个字节的缓冲区
- r - 在 barplot() 中更改大小、颜色和顺序
- java - 获取 Angular 表行数据
- typescript - 来自传播运算符的打字稿联合类型