首页 > 解决方案 > 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;
    }

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

标签: iosswiftuitextfielddelegate

解决方案


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

推荐阅读