應用場景:有時時候從界面A跳轉到界面B,界面B在返回的時候需要將處理的結果傳遞給A.
實現思路:1,定義一個負責傳值的協義,界面A擁有該協義屬性,並實現該協義中的方法
2,界面B也擁有該協義屬性(代理要求兩者都具有相同對象的引用 ),然後在返回的時候獲取界面A的引用指針,並且指定B中協義的調用目標為A,調用協義中的傳值方法.
具體代碼:
A的頭文件 :
#import
@protocol passValueDelegate
-(void) setValue:(NSString *)param;
@end
@interface ViewController : UIViewController
@property
id
@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
@interface ViewController2 : UIViewController
@end
#import "ViewController2.h"
#import "ViewController.h"
@interface ViewController2 ()
@property
id
@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