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
#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.frame=CGRectMake(100, 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
#import <UIKit/UIKit.h>
@interface ViewController2 : UIViewController
@end
#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.frame=CGRectMake(100, 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.passValueDelegate=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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。