按下按钮后,我在小时候添加了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
上设置了带有视图控制器的textField委托。甚至尝试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;
}
但是这种方法永远不会被调用。
答案 0 :(得分:3)
您正在做的是创建SecondViewController
的5个不同实例 - 您通过在每行中调用初始化程序(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)
}