UI 多個視圖控制器(UIViewController)間的 協議傳值

#import <UIKit/UIKit.h>


//1.協議傳值

// 協議由後面的視圖控制器制定

@protocol secondDelegate <NSObject>


//協議的方法需要帶一個或多個參數

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


@end


@interface secondViewController : UIViewController


//2.設置自己的 代理人 屬性

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


@end

==================================================

- (void)buttonAction:(UIButton *)button

{

    NSLog(@"suck");

    //3.讓自己的代理人 調用 協議方法

    [self.delegate passValueWithString:button.currentTitle];

    [self.navigationController popViewControllerAnimated:YES];

}

==================================================

在第二個視圖控制器的 .h 文件的具體方法中  讓自己的代理人 調用 協議方法

- (void)buttonAction:(UIButton *)button

{

    NSLog(@"suck");

    //3.讓自己的代理人 調用 協議方法

    [self.delegate passValueWithString:button.currentTitle];

    [self.navigationController popViewControllerAnimated:YES];

}


==================================================

#import <UIKit/UIKit.h>

#import "secondViewController.h"

//4.由第一個viewController 簽訂 第二個viewController的協議

@interface mainViewController : UIViewController <secondDelegate>


@end


===================================================

在第一個視圖控制器的 .h 文件裏的具體方法中實現 以下:


- (void)buttonAction:(UIButton *)button

{

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

    

    //5.給第二個viewController 指定代理人

    [secondVC setDelegate:self];

    

    [self.navigationController pushViewController:secondVCanimated:YES];

    [secondVC release];

}


//6.實現協議的方法

- (void)passValueWithString:(NSString *)string

{

    NSLog(@"從第二個viewController傳來的值: %@", string);

    UILabel *label = (UILabel *)[self.view viewWithTag:50];

    [label setText:string];

}


發佈了27 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章