UI 多个视图控制器(UIViewController)间的 协议传值

  1 #import <UIKit/UIKit.h>
  2 
  3 
  4 
  5 //1.协议传值
  6 
  7 // 协议由后面的视图控制器制定
  8 
  9 @protocol secondDelegate <NSObject>
 10 
 11 
 12 
 13 //协议的方法需要带一个或多个参数
 14 
 15 - (void)passValueWithString:(NSString *)string;
 16 
 17 
 18 
 19 @end
 20 
 21 
 22 
 23 @interface secondViewController : UIViewController
 24 
 25 
 26 
 27 //2.设置自己的 代理人 属性
 28 
 29 @property (nonatomic, assign) id<secondDelegate> delegate;
 30 
 31 
 32 
 33 @end
 34 
 35 ==================================================
 36 
 37 - (void)buttonAction:(UIButton *)button
 38 
 39 {
 40 
 41     NSLog(@"suck");
 42 
 43     //3.让自己的代理人 调用 协议方法
 44 
 45     [self.delegate passValueWithString:button.currentTitle];
 46 
 47     [self.navigationController popViewControllerAnimated:YES];
 48 
 49 }
 50 
 51 ==================================================
 52 
 53 在第二个视图控制器的 .h 文件的具体方法中  让自己的代理人 调用 协议方法
 54 
 55 - (void)buttonAction:(UIButton *)button
 56 
 57 {
 58 
 59     NSLog(@"suck");
 60 
 61     //3.让自己的代理人 调用 协议方法
 62 
 63     [self.delegate passValueWithString:button.currentTitle];
 64 
 65     [self.navigationController popViewControllerAnimated:YES];
 66 
 67 }
 68 
 69 
 70 ==================================================
 71 
 72 #import <UIKit/UIKit.h>
 73 
 74 #import "secondViewController.h"
 75 
 76 //4.由第一个viewController 签订 第二个viewController的协议
 77 
 78 @interface mainViewController : UIViewController <secondDelegate>
 79 
 80 
 81 
 82 @end
 83 
 84 
 85 
 86 ===================================================
 87 
 88 在第一个视图控制器的 .h 文件里的具体方法中实现 以下:
 89 
 90 
 91 
 92 - (void)buttonAction:(UIButton *)button
 93 {
 94     secondViewController *secondVC = [[secondViewController alloc]init];
 95     
 96     //5.给第二个viewController 指定代理人
 97     [secondVC setDelegate:self];
 98     
 99     [self.navigationController pushViewController:secondVCanimated:YES];
100     [secondVC release];
101 }
102 
103 //6.实现协议的方法
104 - (void)passValueWithString:(NSString *)string
105 {
106     NSLog(@"从第二个viewController传来的值: %@", string);
107     UILabel *label = (UILabel *)[self.view viewWithTag:50];
108     [label setText:string];
109 }

 

posted @ 2016-06-06 15:28  超级马力  阅读(343)  评论(0编辑  收藏  举报