ios 利用Block进行两个页面传值

1. 首先在B页面的头文件中进行block的申明

typedef void(^returnBlock)(NSString *showText);

@interface addddressListViewController : UIViewController


@property (nonatomic, copy) returnBlock returnTextBlock;

- (void)returnText:(returnBlock)block;

@end

在B的实现页面进行传值

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    //即将消失的时候
    
    if (self.returnTextBlock !=nil)
    {
        self.returnTextBlock(@"block 传值测试");//
    }
    NSLog(@"======%@=======",self.returnTextBlock);
}



#pragma mark -
#pragma mark - method

- (void) returnText:(returnBlock)block
{
    self.returnTextBlock = block;
    
}


2. 在A页面初始化Block,实现回调用

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor redColor];
    
    [self initContent];
}

- (void)initContent
{
    _label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30)];
    _label.backgroundColor = [UIColor grayColor];
    _label.textColor = [UIColor yellowColor];

    [self.view addSubview:_label];
    
    
    UIButton *_commitBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 179,80, 45)];
    _commitBtn.backgroundColor = [UIColor grayColor];
    [_commitBtn addTarget:self action:@selector(commitClick) forControlEvents:UIControlEventTouchUpInside];
    [_commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    _commitBtn.titleLabel.textColor = [UIColor whiteColor];
    _commitBtn.layer.cornerRadius = 4;
    [self.view addSubview:_commitBtn];

    _viewConTroller = [[addressListViewController alloc] init];
    
    [_viewConTroller returnText:^(NSString *showText)
    {
             NSLog(@"---------%@------------",showText);
             // self.secTextField.text = showText;
    
             _label.text = showText;
    }];
}

3.  当APP启动时,首先加载的是A页面(初始化Block),然后点击A页面的button跳转到B页面(传值给A页面)。

点击B页面的返回键(回到A页面),此时可以看到从B页面传回给A页面的字符串值  @"block 传值测试"


至此,简答的利用block来进行页面间的传值结束。

你可能感兴趣的:(ios 利用Block进行两个页面传值)