你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> ios 得用代理反向傳值

ios 得用代理反向傳值

編輯:IOS開發綜合

應用場景:有時時候從界面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 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.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


B的頭文件 :


#import


@interface ViewController2 : UIViewController


@end


B的實現文件:


#import "ViewController2.h"

#import "ViewController.h"


@interface ViewController2 ()

@property id 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

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved