iOS  代理的传值使用

来源:互联网 发布:裁剪照片的软件 编辑:程序博客网 时间:2024/06/06 01:34
小弟最近在看ios,看到代理这一块十分蛋疼。参考了一些博客说说的感悟;
iOS的delegate 可用于传值 或者传事件。

首先 我们应该如果呢 
在 ViewController.h 中应该这样写

@protocol Test<</span>NSObject>//定义protocol 


@optional

-(void)TestDelegate:(NSString*)Value ; //定义 delegate 方法


@end


@interfaceViewController : UIViewController

- (IBAction)Next:(id)sender;


@property (nonatomic,assign)id<</span>Test>delegate; //定义delegate 属性

@end

 

在ViewController.m中应该这样写

#import"ViewController.h"

#import"TwoViewController.h"


@interfaceViewController ()


@end


@implementationViewController


- (void)viewDidLoad{

   [superviewDidLoad];

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

}


- (void)didReceiveMemoryWarning{

   [superdidReceiveMemoryWarning];

   // Dispose of any resources that can berecreated.

}


- (IBAction)Next:(id)sender{  //跳转方法

   [self.navigationControllerpopViewControllerAnimated:YES];

   TwoViewController *Two= [[TwoViewController alloc]initWithNibName:@"TwoViewController"bundle:nil]; 

    self.delegate= Two; //设置代理属性 为下一个视图

   [self.delegateTestDelegate:@"fuck"];//执行 protocol方法

}

@end

 

在 TwoViewController.h中应该这样写

#import

#import"ViewController.h"


@interfaceTwoViewController : UIViewController<<span style="font-variant-ligatures: no-common-ligatures;color: #4f8187">Test> //继承 protocol 

{


}

- (IBAction)Back:(id)sender;

-(void)TestDelegate:(NSString*)Value;  //定义 protocol方法

@property NSString*fuck;

@end

 

在 TwoViewController.h中应该这样写

#import"TwoViewController.h"

#import"ViewController.h"

@interfaceTwoViewController () 

@end


@implementationTwoViewController


@synthesize fuck;

- (IBAction)Back:(id)sender{

}

-(void)TestDelegate:(NSString*)Value //实现 protocol 方法

{

  // NSLog(Value);

    self.fuck= Value;

    NSLog(self.fuck);

}

 



主要个人总结一下步骤:

//第一步设置第一个Viewprotocol 并且要继承自NSObeject

//第二步定义protocol 方法 例如TestDelegate(要传的数据)balabala

//第三步定义代理属性delegate

//4 定义代理要穿的下一个函数

//     [self.navigationController popViewControllerAnimated:YES];  取消本斯视图的活动行

//     TwoViewController *Two = [[TwoViewController alloc]initWithNibName:@"TwoViewController" bundle:nil]; 申请要传视图的空间及初始化

//     self.delegate = Two;    自己的代理属性等于那个视图

//     [self.delegate TestDelegate:@"fuck"];  执行代理函数


//5TwoViewController 要继承protocol

//6protocol中的方法

//

//

//代理传值的大体方法如上

 

//CopyRight---Captian






if somewhere wrong,you can connect with me.

0 0
原创粉丝点击