免费开源的iOS开发学习平台

UINavigationController介绍:13-使用代理逆传数据(目标VC->源VC)

导航控制器管理的子控制器之间进行数据传递,除了源控制器向目标控制器传递数据之外,有时目标控制器也需要传递数据给源控制器,例如在目标控制器中修改了一些数据,用户点击返回后,修改后的数据需要显示在源控制器上。当目标控制器需要向源控制器传递数据时,可以使用代理(一对一)或者通知(一对多)。

使用代理实现数据逆传的步骤

下方的示例代码,实现了从目标控制器向源控制器传递数据的过程。

  • 在DestinationViewController.h中,新增代理协议DestinationViewControllerDelegate,并添加一个用于回传数据的代理方法
@class DestinationViewController;
@protocol DestinationViewControllerDelegate <NSObject>
-(void) destinationViewController:(DestinationViewController *) destinationViewController return2SrcVCWithData:(NSString *) string;
@end
  • 在DestinationViewController.h中,新增代理属性
@interface DestinationViewController : UIViewController
@property (nonatomic, weak) id <DestinationViewControllerDelegate> delegate;
@end
  • 在目标控制器中,需要执行popViewController:方法之前,通知代理对象调用代理协议中定义的方法。例如,当点击屏幕时返回源控制器,在返回源控制器之前,调用代理方法,并且传递一个字符串参数(数据)给源控制器。
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if([self.delegate respondsToSelector:@selector(destinationViewController:return2SrcVCWithData:)])
    {
     [self.delegate destinationViewController:self return2SrcVCWithData:@"九九学院"];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
  • 设置SourceViewController类遵守DestinationViewControllerDelegate代理协议
@interface SourceViewController ()<DestinationViewControllerDelegate>
  • 设置目标控制器的代理对象。在SourceViewController.m中,在实例化目标控制器后,设置其代理对象为源控制器
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    DestinationViewController *descVC = [[DestinationViewController alloc] init];
    descVC.view.backgroundColor = [UIColor redColor];
    descVC.navigationItem.title = @"目标控制器";
    
    //跳转前传递数据
    descVC.dataText = @"99iOS.com";
    
    //设置代理
    descVC.delegate = self;
    
    //控制器跳转
    [self.navigationController pushViewController:descVC animated:YES];
}
  • 在SourceViewController.m中,在代理方法中实现具体功能,如,打印传递过来的数据
-(void)destinationViewController:(DestinationViewController *)destinationViewController return2SrcVCWithData:(NSString *)string {
    NSLog(@"目标控制器回传的字符串数据:%@",string);
}

运行结果如下。可以看到回传的数据被打印出来。

示例代码

https://github.com/99ios/9.2.13