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;

    

}



发布了27 篇原创文章 · 获赞 3 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章