Search code examples
iosswiftuitextfielddelegate

UITextFieldDelegate not working for childViewController Swift


I added a SecondViewController as a child after pressing a button. The code below is the button action inside 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)
}

Inside SecondViewController, I set UITextFieldDelegate like this

class SecondViewController: UIViewController, UITextFieldDelegate {

and I set textField delegate with view controller on my xib. Even tried with myTextField.delegate = self. This is my shouldChangeCharactersIn range

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        print("While entering the characters this method gets called")
        return true;
    }

But that method never get called.


Solution

  • What you are doing is creating 5 different instances of SecondViewController - you are doing that by calling initializer (SecondViewController()) in each line

    @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
    }
    

    Do instead

    @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)
    }