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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章