0

Here is the sample source code:

ViewController:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view = Home()
    }

}

Home

class Home: UIView {
    ...
    func parent() -> UIViewController {
        var responder: UIResponder? = self.next
        while responder != nil {
            if let c = responder as? UIViewController { return c }
            else { responder = responder?.next }
        }
        return nil
    }
}

For the line

var responder: UIResponder? = self.next

The responder is always nil, that I cannot get the ViewController.

Something strange is that, I got no problem with the same function for all the subviews of Home.

hanabi_noir
  • 197
  • 1
  • 1
  • 15
  • See the doc of `next`, the discussion part: `For example, UIView implements this method and returns the UIViewController object that manages it (if it has one) or its superview (if it doesn’t).`. So for its subviews it's normal, since default would be their superview. Now, I wonder how does it know what's the ViewController of the view... Could the issue be there? – Larme Sep 07 '21 at 08:29
  • I cannot reproduce this. When are you calling `parent()`? – Sweeper Sep 07 '21 at 08:29
  • @Sweeper I was trying to add `navigationItem` to the parent controller when `init()` the `Home` view. – hanabi_noir Sep 08 '21 at 12:23
  • @Larme Temporarily, I skipped this problem by passing the `ViewController`'s `self` to `Home`'s constructor, and it's working fine. However, I'm wondering why the `next`, which is supposed to be the `ViewController`, is still nil. – hanabi_noir Sep 08 '21 at 12:38

0 Answers0