iOS反向传值

代理传值

要展示的控制器

  • 需要准守<ALTargetViewControllerDeleagte>协议
  • 实现(void)text:(NSString *)text fromVC:(ALTargetViewController *)fromVC indexPath:(nonnull NSIndexPath *)indexPath方法
@interface ALMainViewController ()<ALTargetViewControllerDeleagte>
@end

#pragma mark - ALTargetViewControllerDeleagte

- (void)text:(NSString *)text fromVC:(ALTargetViewController *)fromVC indexPath:(nonnull NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.detailTextLabel.text = text;
}

要反向传值的控制器

  • .h文件需要声明协议,提供一个对外delegate属性,只需要准守我的协议就能成为我的代理对象
@protocol ALTargetViewControllerDeleagte <NSObject>
@optional
- (void)text:(NSString *)text fromVC:(ALTargetViewController *)fromVC indexPath:(NSIndexPath *)indexPath;
@end
@interface ALTargetViewController : UIViewController


@property (nonatomic, weak)id <ALTargetViewControllerDeleagte> delegate;
@end
  • .m文件传递展示控制器需要的内容
- (IBAction)onButton:(id)sender {
    if ([self.delegate respondsToSelector:@selector(text:fromVC:indexPath:)]) {
        [self.delegate text:self.textField.text fromVC:self indexPath:self.indexPath];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

通知传值

要展示的控制器

  • 添加观察者addObserver:
  • 实现通知回调传回的内容(void)alNotification:(NSNotification *)noti
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alNotification:) name:@"ALNotification" object:nil];
}
#pragma mark - Notice
- (void)alNotification:(NSNotification *)noti {
    NSDictionary *dict     = noti.object;
    NSString *text         = dict[@"text"];
    NSIndexPath *indexPath = dict[@"indexPath"];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.text = text;
}

要反向传值的控制器

- (IBAction)onButton:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ALNotification" object:@{@"text":_textField.text, @"indexPath": self.indexPath}];
    [self.navigationController popViewControllerAnimated:YES];
    
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 代理、block、消息中心、单例。 正向传值 通过属性(特性)的值,在上个使用本类(所在类)对象的类中,直接传递其...
    goyohol阅读 877评论 1赞 5
  • 源码下载 简介 最近一直在面试,在准备面试题的时候看到了关于代理传值的问题,自己也是一直对代理这一块比较晕,所以就...
    了念_阅读 353评论 0赞 0
  • 方法三:代码块 根视图代码: //.m文件 -(void)viewDidLoad { [superviewDidL...
    舒耀阅读 3,028评论 0赞 1
  • 本文主要讲解iOS中常见的反向传值方法。 1.AppDelegate传值 在AppDelegate中定义相关的属性...
    断剑阅读 5,083评论 15赞 52
  • 常用的方式 代理 block 通知 也可以使用以下方式但不推荐 单例 全局变量 NSUserDefaults 文件...
    下雨之後阅读 144评论 0赞 0

友情链接更多精彩内容