(有码)Block模式实现导航控制器页面传值

时间:2021-08-31 19:12:34

//在AppDelegate.m中将oneViewController设置为根视图(不会设置的,在目标动作机制传值文章中有)

//TwoViewController.h

#import <UIKit/UIKit.h>

@interface TwoViewController : UIViewController

//声明block属性(相当于声明一个特殊的方法)

@property (nonatomic, copy) void(^twoViewControllerBackItemTouchBlock)(TwoViewController *twoViewController, NSString *string);

@end


//TwoViewController.m

#import "TwoViewController.h"

@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.navigationController popViewControllerAnimated:YES];

   //判断Block是否为nil

    if (self.twoViewControllerBackItemTouchBlock) {

        //block传值

        self.twoViewControllerBackItemTouchBlock(self,@"block逆向传值");

    }

}


//OneViewController.m

#import "OneViewController.h"

#import "TwoViewController.h"

@interface OneViewController ()

@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];

    //实现Block中的方法(注意是setBlock)

    [twoViewController setTwoViewControllerBackItemTouchBlock:^(TwoViewController *twoViewController, NSString *string) {

        self.navigationItem.title = string;

    }];

    

}