(有碼)代理模式導航控制器傳值

//在AppDelegate.m中將oneViewController設置爲根視圖(不會設置的,在目標動作機制傳值文章中有)

//TwoViewController.h

#import <UIKit/UIKit.h>

@class TwoViewController;

//聲明代理方法

@protocol TwoViewControllerDelegate <NSObject>

- (void)twoViewControllerBackItems:(TwoViewController *)twoViewController setTitle:(NSString *)string;

@end


@interface TwoViewController : UIViewController


//聲明代理屬性

@property (nonatomic, weak) id<TwoViewControllerDelegate>delegate;

@end


//TwoViewController.h

#import "TwoViewController.h"

@class OneViewController;

@interface TwoViewController ()

@end

@implementation TwoViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    //設置返回按鈕

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(btnClick)];

}


//設置點擊事件,觸發代理方法

- (void)btnClick{

    [self.delegate twoViewControllerBackItems:self setTitle:@"第一個按鈕"];

    

    [self.navigationController popViewControllerAnimated:YES];

}

//OneViewController.m

#import "OneViewController.h"

#import "TwoViewController.h"

@interface OneViewController ()<TwoViewControllerDelegate>

@end

@implementation OneViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

}

//跳轉到第二個頁面

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    

    TwoViewController *twoViewController = [[TwoViewController alloc]init];

    [self.navigationController pushViewController:twoViewController animated:YES];

    //綁定代理

    twoViewController.delegate = self;

}

//實現代理方法

- (void)twoViewControllerBackItems:(TwoViewController *)twoViewController setTitle:(NSString *)string{

    //將導航條標題改變

    self.navigationItem.title = string;

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章