ios - UITextFieldDelegate 不适用于 childViewController Swift
问题描述
SecondViewController
按下按钮后,我添加了一个孩子。下面的代码是里面的按钮动作MainViewController
。
@IBAction func btnPressed(_ sender: Any) {
addChildViewController(SecondViewController())
view.superview?.addSubview(SecondViewController().view)
SecondViewController().view.frame = (view.superview?.bounds)!
SecondViewController().view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
SecondViewController().didMove(toParentViewController: self)
}
里面SecondViewController
,我UITextFieldDelegate
这样设置
class SecondViewController: UIViewController, UITextFieldDelegate {
我在我的xib
. 甚至尝试过myTextField.delegate = self
. 这是我的shouldChangeCharactersIn range
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("While entering the characters this method gets called")
return true;
}
但是该方法永远不会被调用。
解决方案
您正在做的是创建 5 个不同的实例- 您通过在每一行中SecondViewController
调用初始化程序 ( ) 来做到这一点SecondViewController()
@IBAction func btnPressed(_ sender: Any) {
addChildViewController(SecondViewController()) // first instance created
view.superview?.addSubview(SecondViewController().view) // second instance created
SecondViewController().view.frame = (view.superview?.bounds)! // third instance created
SecondViewController().view.autoresizingMask = [.flexibleWidth, .flexibleHeight] // fourth instance created
SecondViewController().didMove(toParentViewController: self) // fifth instance created
}
改为
@IBAction func btnPressed(_ sender: Any) {
let secondViewController = SecondViewController()
addChildViewController(secondViewController)
view.superview?.addSubview(secondViewController.view)
secondViewController.view.frame = (view.superview?.bounds)!
secondViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
secondViewController.didMove(toParentViewController: self)
}
推荐阅读
- javascript - jquery onclick 事件不适用于链接
- java - 在 Java 中为 AWS IoT 创建自签名证书
- java - Android can't inflate layout file with attrs values
- javascript - 如何从我的 chrome 扩展中替换代码?
- coq - 后跟数字的“归纳”策略有什么作用?
- tsql - 如何在 Grafana 上显示自上次空值以来的时间
- stripe-payments - 为什么 Stripe Google Pay 按钮没有在 UI 上为我呈现,尽管没有任何错误或异常?
- node.js - 在节点中运行我的文件,终端在意外标记 `(' 附近抛出错误语法错误
- c++ - C ++从文件中读取和打印换行符
- python - JSON 错误:json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)