ios block传值 最简单的方法

本文介绍了一种使用Block在iOS应用的不同视图控制器间传递数据的方法。通过声明并利用Block类型属性,可以在控制器之间灵活地传递参数,实现了从一个视图控制器向另一个视图控制器传递整型数据的功能。

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

1、在您需要传值出去的控制器头文件里声明:

@property (nonatomic,copy) void(^stringblockr)(int age);


2、然后在你pop或者push到被传值的页面的方法里,调用该方法:

self.stringblockr(15);


3、在被传值的控制器中吊用你传值页面刚申明的方法:

 SecondViewController *send = [[SecondViewController alloc]init];

    

    send.stringblockr = ^(int age) {

        NSLog(@"%d",age);

    };



以下是整个流程:

#import <UIKit/UIKit.h>


@interface SecondViewController : UIViewController


@property (nonatomic,copy) void(^stringblockr)(int age);


@end




#import "SecondViewController.h"


@interface SecondViewController ()


@end


@implementation SecondViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor purpleColor];

    

    UIButton *ba = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100,50)];

    ba.backgroundColor = [UIColor blueColor];

    [ba addTarget:self action:@selector(popAction) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:ba];


}


- (void)popAction {

    self.stringblockr(15);

    [self.navigationController popViewControllerAnimated:YES];

    

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];


}



#import "ViewController.h"

#import "SecondViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    self.view.backgroundColor = [UIColor redColor];

    

    

}

- (IBAction)btnClick:(id)sender {

    

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 100, 100, 30)];

    [self.view addSubview:label];

    

    label.backgroundColor = [UIColor orangeColor];

    

    SecondViewController *send = [[SecondViewController alloc]init];

    

    send.stringblockr = ^(int age) {

        NSLog(@"%d",age);

    };

    

    [self.navigationController pushViewController:send animated:YES];

    

    

    

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值