1. typedef void(^myBlock)(int a ,int b);// 第一种方式
#import <UIKit/UIKit.h>
typedef void(^myBlock)(int a ,int b);// 第一种方式
@interface BlockView : UIView
{
myBlock myblock;
}
@property (nonatomic, strong) UIButton *btn;
- (void)initWithBlock:(myBlock)sendAB;
@end
#import "BlockView.h"
@implementation BlockView
@synthesize btn;
- (void)initWithBlock:(myBlock)sendAB
{
myblock = sendAB;
btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100, 100, 100, 50);
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn];
}
- (void)click
{
myblock(1,2);
}
@end
#import "ViewController.h"
#import "BlockView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
BlockView * view = [[BlockView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[view initWithBlock:^(int a, int b) {
[view.btn setTitle:[NSString stringWithFormat:@" 1 + 2 = %d",a+b] forState:UIControlStateNormal];
}];
[view.btn setTitle:@"1 + 2 = ?" forState:UIControlStateNormal];
[self.view addSubview:view];
}
@end
2. block作为属性传值
@property (nonatomic, copy) void(^myBlock2)(int a, int b); // 第二种方式
#import <UIKit/UIKit.h>
@interface BlockView : UIView
@property (nonatomic, strong) UIButton *btn;
- (void)initWithView;
@property (nonatomic, copy) void(^myBlock2)(int a, int b); // 第二种方式
@end
#import "BlockView.h"
@implementation BlockView
@synthesize btn;
- (void)initWithView;
{
btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100, 100, 100, 50);
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn];
}
- (void)click
{
self.myBlock2(1,2);
}
@end
#import "ViewController.h"
#import "BlockView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
BlockView * view = [[BlockView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[view initWithView];
[view.btn setTitle:@"1 + 2 = ?" forState:UIControlStateNormal];
__block BlockView * viewBG = view;
view.myBlock2 = ^(int a, int b){
[viewBG.btn setTitle:[NSString stringWithFormat:@"1 + 2 = %d",a+b] forState:UIControlStateNormal];
};
[self.view addSubview:view];
}
@end