Communication between Controllers in iOS [duplicat

2019-03-04 13:46发布

问题:

This question already has an answer here:

  • Passing Data between View Controllers 41 answers

I am learning iOS development using Obejctive-C for the last week now and I can't figure out how to communicate between controllers. This is my storyboard:

The Routes Page View Controller is a PageViewController embedded inside the container view.

In the MapViewController I want to access the RoutesPageViewController to call some methods. But when I make an outlet to the container view in my MapViewController and cast it to RoutesPageViewController and call a method it throws this error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView items]: unrecognized selector sent to instance 0x7ff60551a300'

Which is logic because it's not a RoutesPageViewController.

So my question is since I will encounter this issue in my further iOS development career: What are the good ways to communicate between Controllers?

Thanks in advance.

回答1:

ContainerView is just a UIView. It doesn't have any reference of embedded ViewController. It creates a Parent-Child relationship between viewcontrollers. Like here, MapViewController is a parent and RoutesPageViewController is a child.

Now, for getting reference of child you should use childViewControllers property of ViewController. It will return an array of child ViewControllers.

Like here in MapViewController

let routeVC : RoutesPageViewController? = self.childViewControllers.filter{$0 is RoutesPageViewController}.first

will give you the reference of RoutesPageViewController.