一、block延伸:页面间反向传值

1)first页面的代码

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupBtn];
    self.view.backgroundColor = [UIColor whiteColor];
    
}
- (void)setupBtn
{
    UIButton * btn = [[UIButton alloc]init];
    [btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor = [UIColor blackColor];
    btn.frame = CGRectMake(100, 100, 100, 100);
    [self.view addSubview:btn];
}
- (void)buttonClick
{
    SecondViewController * secondVC = [[SecondViewController alloc]init];
    //在first页面调用block输出字符串
    secondVC.myBlock= ^(NSString * str){
        NSLog(@"%@",str);
    };
    [self.navigationController pushViewController:secondVC animated:YES];
}

2)second页面的代码

//.h文件
#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController
//定义block
@property (nonatomic,copy)void (^myBlock)(NSString * str);
@end
//.m文件
- (void)setupBtn
{
    UIButton * btn = [[UIButton alloc]init];
    [btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor = [UIColor blackColor];
    btn.frame = CGRectMake(100, 100, 100, 100);
    [self.view addSubview:btn];
}
- (void)buttonClick
{
    //通过block传值
    if (self.myBlock) {
        self.myBlock(@"haha");
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}

输出结果:

2016-02-19 11:36:55.168 03-block[983:70116] haha

参考博客:http://my.oschina.net/leejan97/blog/268536?fromerr=2UdIND3G

相关文章:

  • 2021-12-18
  • 2022-01-19
  • 2021-11-21
  • 2021-06-18
  • 2021-12-02
  • 2021-06-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-04-15
  • 2021-08-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-16
相关资源
相似解决方案