• 爱情文章
  • 亲情文章
  • 友情文章
  • 生活随笔
  • 校园文章
  • 经典文章
  • 人生哲理
  • 励志文章
  • 搞笑文章
  • 心情日记
  • 英语文章
  • 范文大全
  • 作文大全
  • 新闻阅读
  • 当前位置: 山茶花美文网 > 亲情文章 > 正文

    父组件调用子组件的方法【开发IOS关于子UIViewController和父UIViewController相互调用方法】

    时间:2020-05-29来源:山茶花美文网 本文已影响 山茶花美文网手机站

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

    • 父组件调用子组件的方法【开发IOS关于子UIViewController和父UIViewController相互调用方法】 相关文章:
    • 爱情文章
    • 亲情文章
    • 友情文章
    • 随笔
    • 哲理
    • 励志
    • 范文大全