Search code examples
swiftuiresponderuievent

iOS Responder Chain and Events


I'm a little confused. There are two UIViewControllers in UINavagationController's stack. I try to call the method of first UIViewController within the second UIViewController. See code below

class VC1: UIViewController {

    @objc func method1() {
        //not called after tap button
    }
}

class VC2: UIViewController {

    let button = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        button.addTarget(nil, action: #selector(VC1.method1), for: .touchUpInside)
    }
}

But method1 isn't called when I tap on the button. What's the problem?


Solution

  • The responder chain is based on superviews and parent view controllers. So VC1 is not up the responder chain from VC2. The responder chain from VC2 leads to its parent (the UINavigationController); it does not go by way of any other children of the UINavigationController.