前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >iOS视图控制器之间delegate传值教程

iOS视图控制器之间delegate传值教程

作者头像
全栈程序员站长
发布2022-07-07 19:47:27
发布2022-07-07 19:47:27
5690
举报

大家好,又见面了,我是全栈君。

之前在StackOverFlow上看到一篇讲传值(segue传值和delegate传值)的文章,感觉讲的非常清晰,就将delegate部分翻译了一下。有兴趣能够看看。

原文:

http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers

译文:

为了从ViewControllerB往回传值到ViewControllerA,我们须要使用协议(Protocols)和代理(Delegates)。

为了实现这个过程,我们须要设置ViewControllerA为ViewControllerB的代理。

这样可以使ViewControllerB可以发送消息到ViewControllerA,相同也能使我们将数据回传。

ViewControllerA作为ViewControllerB的代理必需要遵从我们在ViewControllerB中定义的协议(Protocols),这可以告诉ViewControllerA有哪些方法是必需要实现的。

1.在ViewControllerB.h中,在#import和@interface之间(就是代码位置)。我们像以下这样定义我们的协议及协议方法:

@classViewControllerB;// Important @protocol ViewControllerBDelegate <NSObject> – (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item; @end

注:(NSString *)item是我们如今要回传的数据类型,也能够是其它类型,如字典、数组等

2.仍然是在ViewControllerB.h中。设置一个delegate属性,同一时候在ViewController.m中synthesize

@property (nonatomic, weak) id <ViewControllerBDelegate>delegate;

在project中我是这么做的:

@propertyid<SelectPeopleVCDelegate>delegate;

3. 在 ViewControllerB 中,我们在将要从导航控制器中弹出该视图的时候向代理发送消息 ( 消息中含有我们要传递的值 )

NSString *itemToPassBack = @“Pass this value back to ViewControllerA”; [self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];

在实际project中我是这样完毕的:

– (void)viewDidDisappear:(BOOL)animated

{

[self.delegateaddItemViewController:selfdidFinishSelectPeople:dataSourceArray];

}

注:dataSourceArray是我的数据源,在一个公开变量,在前面的程序中完毕赋值。

4. 以上就是全部要在 ViewControllerB 中进行的操作。接下来就是 ViewControllerA 的操作。

首先我们要在ViewControllerA.h中导入ViewControllerB,并遵从它的协议:

#import “ViewControllerB.h” @interface ViewControllerA :UIViewController <ViewControllerBDelegate>

5.在ViewControllerA.m中实现协议方法:

– (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item { NSLog(@“This was returned from ViewControllerB %@”,item); }

6.最后,在我们将ViewControllerB压入堆栈之前,我们须要告诉ViewControllerB,ViewControllerA是它的代理(delegate)

ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@“ViewControllerB” bundle:nil]; viewControllerB.delegate = self [[self navigationController] pushViewController:viewControllerB animated:YES];

在实际project中我是这样做的:

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

{

UIViewController * viewController = segue.destinationViewController;

BAGSelectPeopleVC * selectPeopleVC = (BAGSelectPeopleVC *)viewController;

selectPeopleVC.delegate =self;

}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/116356.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年1月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档