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

 2023-09-05 阅读 58 评论 0

摘要:之前在StackOverFlow上看到一篇讲传值(segue传值和delegate传值)的文章,感觉讲的非常清晰,就将delegate部分翻译了一下。有兴趣能够看看。 原文: http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers 译文

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

原文:

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


译文:

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

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

这样可以使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.msynthesize

 

@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压入堆栈之前,我们须要告诉ViewControllerBViewControllerA是它的代理(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://hbdhgg.com/3/1263.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息