Block 两个界面之间传值

87 篇文章 0 订阅

首先要意识到,block的本质,block本身就是一个函数。

所以,block传值就是利用block的声明,定义,调用这三个步骤即可以实现。

第一步:声明,需要我们在要传值的界面声明一个block的功能,也包括要传递的参数的类型。

第二步:定义,需要我们在要接收值的界面定义block的具体实现细节,比如说,把传递过来的形参赋给谁。

第三步:调用,需要我们在要传值的界面调用block,把实参传递出去。



第二个界面的代码片段:

//1.取别名

typedef void(^PassValueBlock)(NSString *text);


@interface CustomViewController : UIViewController


//2.写成属性,因为外界要访问

@property(nonatomic,strong) PassValueBlock passValueBlock;


@end

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

#import "CustomViewController.h"


@interface CustomViewController ()<UITextFieldDelegate>


@property(nonatomic,strong) UITextField *textField;


@end


@implementation CustomViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    

    self.textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 100, 200, 40)];

    _textField.borderStyle = UITextBorderStyleRoundedRect;

    

    _textField.placeholder = @"输入点什么";

    

    [self.view addSubview:_textField];

    

    _textField.delegate = self;

    

    self.navigationItem.title = @"第二页";

    

}


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

{

    

    //使用部分

    self.passValueBlock(_textField.text);

    

    //返回上一个

    [self dismissViewControllerAnimated:YES completion:nil];

}


@end

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

第一个界面需要接收值:

#import "RootViewController.h"


#define  kScreenWith [UIScreen mainScreen].bounds.size.width

#define kScreenHeight [UIScreen mainScreen].bounds.size.height


@interface RootViewController ()


@property(nonatomic,strong) UILabel *label;


@end


@implementation RootViewController



- (void)viewDidLoad {

    [super viewDidLoad];

    

    self.view.backgroundColor = [UIColor whiteColor];

    

    

    self.label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 40)];

    _label.backgroundColor = [UIColor whiteColor];

    _label.textColor = [UIColor redColor];

    _label.text = @"你想说什么";

    

    [self.view addSubview:_label];

    

    self.navigationItem.title = @"第一页";

    

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editAction:)];

}


-(void)editAction:(id)sender

{

    

}


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

{

    

    CustomViewController *customVC = [[CustomViewController alloc]init];

    

    //展开部分--实现

    customVC.passValueBlock = ^(NSString *text)

    {

        _label.text = text;

    };

    

    [self showDetailViewController:customVC sender:nil] ;

    

}




- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值