在iPhone开发中关于子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相互交互的方法和思路,如果有什么错误或者弊端还希望大家能够提出来我们共同探讨

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值