声明创建block:
#import <UIKit/UIKit.h>
@class BlockTestView;
//定义block
typedef void(^testBlock)(NSString *str);
@interface BlockTestView : UIView
//属性
@property(nonatomic ,copy)testBlock test;
+(BlockTestView *)testView;
//加到方法中的
-(void)testTestViewBlock:(testBlock)test;
@end
#import "BlockTestView.h"
@implementation BlockTestView
+(BlockTestView *)testView{
return [[[NSBundle mainBundle] loadNibNamed:@"BlockTestView" owner:nil options:nil] firstObject];
}
- (IBAction)blockTestButton:(UIButton *)sender {
self.test(@"123");
}
-(void)testTestViewBlock:(testBlock)test{
test(@"456");
}
@end
控制器中的调用
#import "ViewController.h"
#import "BlockTestView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
BlockTestView *testView = [BlockTestView testView];
[self.view addSubview:testView];
//属性
testView.test = ^(NSString *str){
NSLog(@"%@",str);
};
//方法
[testView testTestViewBlock:^(NSString *str) {
NSLog(@"%@",str);
}];
}
@end