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

@property
id<passValueDelegate> passValueDelegate;

@end


  A的实现文件 :

#import "ViewController.h"

#import "ViewController2.h"

@interface
ViewController ()

{

}

@end

@implementation ViewController

- (void)viewDidLoad

{

[super
viewDidLoad];

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

UIButton *btn =[UIButton
buttonWithType:UIButtonTypeRoundedRect];

btn.,
100, 200,
40);

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

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

[self.view
addSubview:btn];

self.view.backgroundColor=[UIColor
redColor];

}

-(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"

@interface
ViewController2 ()

@property
id<passValueDelegate> passValueDelegate;

@end

@implementation ViewController2

- (void)viewDidLoad

{

[super
viewDidLoad];

UIButton *btn =[UIButton
buttonWithType:UIButtonTypeRoundedRect];

btn.,
100, 200,
40);

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

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

[self.view
addSubview:btn];

}

-(void)btn

{

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

];

[self.navigationController
popToRootViewControllerAnimated:YES];

[self.passValueDelegate
setValue:@"123456789"];

}

- (void)didReceiveMemoryWarning

{

[super
didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

上一篇:[置顶] 老孟 DB2 V9.7 ESE(一)产品部署 基于centOS 6.4


下一篇:利用协议代理实现导航控制器UINavigationController视图之间的正向传值和反向传值