UITextFieldDelegate 不适用于 childViewController Swift

UITextFieldDelegate not working for childViewController Swift

我在按下按钮后添加了一个 SecondViewController 作为 child。下面的代码是 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;
    }

但是那个方法永远不会被调用。

您正在做的是创建 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)
}