首页 > 代码库 > ios 得用代理反向传值

ios 得用代理反向传值

   应用场景:有时时候从界面A跳转到界面B,界面B在返回的时候需要将处理的结果传递给A.

   实现思路:1,定义一个负责传值的协义,界面A拥有该协义属性,并实现该协义中的方法

                       2,界面B也拥有该协义属性(代理要求两者都具有相同对象的引用 ),然后在返回的时候获取界面A的引用指针,并且指定B中协义的调用目标为A,调用协义中的传值方法.

 具体代码:

    A的头文件 :


#import <UIKit/UIKit.h>

@protocol passValueDelegate <NSObject>

-(void) setValue:(NSString *)param;


@end


@interface ViewController :UIViewController

@propertyid<passValueDelegate> passValueDelegate;

@end


  A的实现文件 :

 


#import "ViewController.h"

#import "ViewController2.h"



@interfaceViewController ()

{


}


@end



@implementation ViewController


- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    UIButton *btn =[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    btn.frame=CGRectMake(100,100, 200,40);

    [btn setTitle:@"btn"forState:UIControlStateNormal];

    [btn addTarget:selfaction:@selector(btn)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:btn];

    

    self.view.backgroundColor=[UIColorredColor];

}


-(void) setValue:(NSString *)param{

    NSLog(@"pass value is:%@",param);

}

-(void)btn

{

    [self.navigationController pushViewController:[[ViewController2 alloc]init] animated:YES];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


B的头文件 :

 


#import <UIKit/UIKit.h>


@interface ViewController2 :UIViewController


@end


B的实现文件:


#import "ViewController2.h"

#import "ViewController.h"


@interfaceViewController2 ()

@propertyid<passValueDelegate> passValueDelegate;

@end


@implementation ViewController2


- (void)viewDidLoad

{

    [superviewDidLoad];

    UIButton *btn =[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    btn.frame=CGRectMake(100,100, 200,40);

    [btn setTitle:@"back"forState:UIControlStateNormal];

    [btn addTarget:selfaction:@selector(btn)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:btn];

}

-(void)btn

{

  //  NSLog(@"%@",self.navigationController.childViewControllers[0]);

    self.passValueDelegate=self.navigationController.childViewControllers[0];

    [self.navigationControllerpopToRootViewControllerAnimated:YES];

   

    [self.passValueDelegatesetValue:@"123456789"];

}




- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end