@interface MyView : UIView
typedef void(^SuccessBlock)(NSString *log);
@property (copy,nonatomic)SuccessBlock successBlock;
- (void)clickOperationWithSuccessBlock:(SuccessBlock)successBlock;
@end
@implementation MyView
-(instancetype)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeCustom];
[btn setTitle:@"点击"forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColorblueColor]];
[btn addTarget:selfaction:@selector(click)forControlEvents:UIControlEventTouchUpInside];
[btn setFrame:CGRectMake(10,10,100, 30)];
[self addSubview:btn];
}
return self;
}
-(void)click
{
NSString *str = [NSStringstringWithFormat:@"%u",arc4random_uniform(100)];
self.successBlock(str);
}
-(void)clickOperationWithSuccessBlock:(SuccessBlock)successBlock{
self.successBlock = successBlock;
}
@end
使用
@interface ViewController ()
@property (strong,nonatomic) MyView *mv;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.mv];
}
-(MyView *)mv{
if (!_mv) {
_mv = [[MyView alloc]initWithFrame:CGRectMake(10, 10, 300, 300)];
[_mv clickOperationWithSuccessBlock:^(NSString *log) {
NSLog(@"%@",log);
}];
return _mv;
}
return _mv;
}
@end