iOS中使用Block反响传值的用法

本文介绍了在iOS开发中,如何使用Block实现从B页面向A页面的逆向传值,相较于代理方式,Block的代码更加简洁。通过示例代码详细展示了在A页面的.h文件中声明Block的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 方向传值,用block传值要比用代理传值简单多,并且代码简单。

有一个A页面和B页面,B页面的值传给A页面,这就是用Block方向传值。

下面直接上代码

A页面代码

UIButton * playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    playButton.frame = CGRectMake(100, 220, 100, 80);
    [playButton setTitle:@"选择播放视频" forState:UIControlStateNormal];
    [playButton setBackgroundColor:[UIColor grayColor]];
    [playButton addTarget:self action:@selector(playVideoGo) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:playButton];
    
    self.textLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 320, 100, 30)];
    self.textLabel.backgroundColor = [UIColor greenColor];
    [self.textLabel setText:@"回调传值"];
    [self.view addSubview:self.textLabel];

- (void)playVideoGo {
    playVideoViewController * vc = [[playVideoViewController alloc] init];
    vc.returnBlock = ^(NSString * showText){
        NSLog(@"----------%@",showText);
        self.textLabel.text = showText;
    };
    [self presentViewController:vc animated:YES completion:nil];
    //[self.navigationController pushViewController:vc animated:YES];
}

B页面代码如下:

在.h文件里申明一个Block

typedef void (^ReturnTextBlock)(NSString * showText);
在.m文件中

self.inputFiled = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 30)];
    self.inputFiled.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.inputFiled];
    
    
    
    UIButton * playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    playButton.frame = CGRectMake(100, 220, 100, 80);
    [playButton setTitle:@"回调" forState:UIControlStateNormal];
    [playButton setBackgroundColor:[UIColor grayColor]];
    [playButton addTarget:self action:@selector(playVideoBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:playButton];
 
-(void)playVideoBack {
    self.returnBlock(self.inputFiled.text);
    [self dismissViewControllerAnimated:YES completion:nil];
    //[self.navigationController popViewControllerAnimated:YES];
}

这样即可完成页面反响传值。。。。。。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值