一群程序猿的秘密基地iOS 开发

Block传值

2016-05-23  本文已影响90人  i赵磊

效果图

ViewController.m

#import "ViewController.h"
#import "ZLViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor redColor];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    ZLViewController*zlController=[[ZLViewController alloc]init];
    //防止循环引用
    __weak typeof(self)weakSelf=self;
    //block的实现
    zlController.myBlock=^(UIColor*color){
    //来回调此块代码时color已经有值。
        weakSelf.view.backgroundColor=color;
    };
    [self presentViewController:zlController animated:YES completion:nil];
}
@end

ZLViewController.h

#import <UIKit/UIKit.h>
typedef void (^ByValueBlock)(UIColor*);
@interface ZLViewController : UIViewController
@property(strong,nonatomic)ByValueBlock myBlock;
@end

ZLViewController.m

#import "ZLViewController.h"
@interface ZLViewController ()
@end
@implementation ZLViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor blueColor];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UIColor*color=[UIColor grayColor];
    //block的调用(赋值)
    self.myBlock(color);
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
上一篇 下一篇

猜你喜欢

热点阅读