标题 | 开发IOS关于子UIViewController和父UIViewController相互调用方法 |
内容 | 今天在做iphone开发时碰到了一个常用的需求,即在一个viewController中添加另外一个viewController,同时能保证这两个ViewController之间能够相互交互且相互调用方法和函数,在网上查了很多资料,很多开发者说需要使用objective-c变态的 delegate,可是我感觉delegate是使用在两个同级之间的UIView比较好,至于能不能使用在父子关系而且是 UIVeiwController我也不太清楚,也没有亲自实验过,通过查看SDK的API及其他资料我使用了自己的方法实现了我想要的需求,但是我不知道我的这种方法会不会有致命性的问题,或者会不会有很大的弊端,如果有高人存在的话还望指点一下,我只是一个初学者,下面我将我的方法贴上来: 首先,定义两个UIVeiwController,姑且先命名为ViewControllerParent(父容器)和ViewControllChild(子容器)吧,我们可以通过UIView的 insertSubview方法将子容器添加到父容器中,这点在这里先不用说了 其次,我们先来看一下通过父容器调用子容器中的方法及函数,我先在子容器ViewControllChild和父容器ViewControllerParent中分别写了如下方法: //该方法是弹出一个警告框 -(void)AlertWindow:(NSString *)transValue{ UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:transValue message:transValue delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; [alertView release]; } 由于父容器ViewControllerParent要插入ViewControllChild,因此在ViewControllerParent一定已经定义了ViewControllChild,如下: @synthesize ViewControllChild; if (self.ViewControllChild==nil) { ViewControllChild *ViewControll=[[ViewControllChild alloc] initWithNibName:@"ViewControllChild" bundle:nil]; self.ViewControllChild=ViewControll; [ViewControll release]; } 所以当父容器调用子容器的方法只需要做下面一步即可: [self.ViewControllChild AlertWindow:@"我是从子容器中弹出来的"]; 这就实现了父容器调用子容器中方法; 最后,看一下如何在子容器中调用父容器的方法,我的思路是这样的,在insertSubview时我设置该子容器的父Controller,最后在子容器中通过父Controller来调用方法,因此我在子容器ViewControllChild中添加了一个这样的方法: //设置当前窗口的父容器 -(void)SetParentView:(UIViewController *)viewController{ [self setParentViewController:viewController]; } 在ViewControllerParent实现insertSubview前加入下边代码: [self.ViewControllChild SetParentView:self]; 该代码实现了设置父容器 这样在子容器ViewControllChild中通过以下代码就可以调用父容器的方法或者函数了: [self.parentViewController AlertWindow:@"我是从父容器中弹出来的"]; 以上便是实现ViewController相互交互的方法和思路,如果有什么错误或者弊端还希望大家能够提出来我们共同探讨 |
随便看 |
|
在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。