iOS中控制器之间的通信 [英] Communication between Controllers in iOS
问题描述
我上周正在学习使用Obejctive-C进行iOS开发,但我不知道如何在控制器之间进行通信. 这是我的故事板:
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:
Routes Page View Controller
是嵌入在容器视图内的PageViewController
.
The Routes Page View Controller
is a PageViewController
embedded inside the container view.
在MapViewController
中,我想访问RoutesPageViewController
来调用某些方法.
但是,当我在MapViewController
中对容器视图进行出口并将其转换为RoutesPageViewController
并调用方法时,它将引发此错误:
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'
这是逻辑,因为它不是RoutesPageViewController
.
Which is logic because it's not a RoutesPageViewController
.
所以我的问题是,因为我在以后的iOS开发生涯中会遇到此问题:在Controller之间进行通信的好方法是什么?
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?
谢谢.
推荐答案
ContainerView只是一个UIView.它没有嵌入式ViewController的任何引用.它在视图控制器之间创建父子关系.像这里一样,MapViewController
是父母,RoutesPageViewController
是孩子.
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.
现在,为了获取孩子的引用,您应该使用ViewController
的childViewControllers
属性.它将返回一个子ViewControllers数组.
Now, for getting reference of child you should use childViewControllers
property of ViewController
. It will return an array of child ViewControllers.
就像MapViewController
let routeVC : RoutesPageViewController? = self.childViewControllers.filter{$0 is RoutesPageViewController}.first
将为您提供RoutesPageViewController
的参考.
这篇关于iOS中控制器之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!