如果當前有兩個視圖控制器 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;
- (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;
}