block传值(1)两个界面间传值

有两个界面A—>B,现将B界面的值传到A界面,应在B界面进行block的声明以及实现

B界面代码如下:

#import <UIKit/UIKit.h>

typedef void(^SendNumBlock)(NSString *num);

@interface ZJNextViewController : UIViewController

-(void)sendNum:(SendNumBlock)block;

@end

#import "ZJNextViewController.h"

@interface ZJNextViewController ()

@end

@implementation ZJNextViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(100, 200, 50, 50);
    [button setBackgroundColor:[UIColor orangeColor]];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

}

-(void)sendNum:(SendNumBlock)block
{
    block(@"yan");
}

-(void)back
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

A界面在需要调用的时候 调用B界面的block方法即可

#import "ViewController.h"
#import "ZJNextViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(100, 200, 50, 50);
    [button setBackgroundColor:[UIColor orangeColor]];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitle:@"跳转" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    nextBtn.frame = CGRectMake(200, 300, 50, 50);
    [nextBtn setBackgroundColor:[UIColor orangeColor]];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextBtn setTitle:@"传值" forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(showText) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
}

-(void)showText
{
    ZJNextViewController *nextVc = [[ZJNextViewController alloc]init];
    [nextVc sendNum:^(NSString *num) {
        NSLog(@"viewController:%@",num);
    }];
}



-(void)push
{
    ZJNextViewController *nextVc = [[ZJNextViewController alloc]init];

    [self presentViewController:nextVc animated:YES completion:nil];
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值