Communication between Controllers in iOS [duplicat

2019-03-04 13:43发布

This question already has an answer here:

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: enter image description here

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条回答
做个烂人
2楼-- · 2019-03-04 14:34

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.

查看更多
登录 后发表回答