UI 设置代理 实现视图控制器间的传值操作

如果当前有两个视图控制器 MainViewController 和 SecondViewController

实现让SecondViewController 传值给 MainViewController  :

1. 首先在 SecondViewController.h 

 

 

 

 

// 1. 协议传值

// 协议由后面的视图控制器制定

 

@protocol SecondDelegate <NSObject>

// 传值协议的方法需要带一个或多个参数

- (void) passValueWithString:(NSString *)string;

 

@end

 

@interface SecondViewController : UIViewController

// 2.设置自己的 代理人 属性

 

@property (nonatomic, assign) id<SecondDelegate>delegate;

 

2. 在 SecondViewController.m 的实现方法中:

 

- (void)buttonClicked:(UIButton *)button

{

    // 3. 让自己的代理人 调用 协议方法

    [self.delegate passValueWithString:button.currentTitle];

    

}

 

3. 在MainViewController.h 中:

 

// 4. 由第一个视图控制器 签订 第二个视图控制器的协议

@interface MainViewController : UIViewController<SecondDelegate>

 

4. 在MainViewController.m 中:

 

- (void)buttonClicked:(UIButton *)button

{

    SecondViewController *secondVC = [[SecondViewController alloc] init];

    

    // 5. 给第二个视图控制器 指定代理人

    secondVC.delegate = self;

    

}

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