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