二十二, iOS UIButton的Block的使用

3/1/2017来源:Android开发人气:479

一,首先对button定义block

#import <UIKit/UIKit.h> #import <objc/runtime.h> typedef void (^ActionBlock)();//声明block @interface UIButton (Block) @PRoperty (readonly) NSMutableDictionary *event;//事件 - (void) handleControlEvent:(UIControlEvents)controlEvent withBlock:(ActionBlock)action;//方法 @end

二,.m文件代码如下 #import "UIButton+Block.h" @implementation UIButton (Block) static char overviewKey; @dynamic event; - (void)handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)block {     if (block) {         objc_removeAssociatedObjects(self);                  objc_setAssociatedObject(self, &overviewKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);         [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];     } } - (void)callActionBlock:(id)sender {     ActionBlock block = (ActionBlock)objc_getAssociatedObject(self, &overviewKey);     if (block) {         block();     } } 三,导入文件#import "UIButton+Block.h",和调用

UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(10, 100, self.view.frame.size.width-20,60 )];     [button setTitle:@"block" forState:UIControlStateNormal];     button.backgroundColor =[UIColor redColor];     [button handleControlEvent:UIControlEventTouchUpInside withBlock:^{         NSLog(@"button block");     }];     [self.view addSubview:button];