首页 > 系统 > iOS > 正文

二十二, iOS UIButton的Block的使用

2019-11-06 09:34:28
字体:
来源:转载
供稿:网友

一,首先对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];


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表