- 给UIBarButtonItem添加一个
Block
分类
#import <UIKit/UIKit.h>
@interface UIBarButtonItem (BlockSupport)
- (nullable instancetype)initWithTitle:(nullable NSString *)title style:(UIBarButtonItemStyle)style andBlock:(void(^)())clickBlock;
@end
#import "UIBarButtonItem+BlockSupport.h"
#import <objc/runtime.h>
const char *barbuttonItemBlockKey = "barbuttonItemBlockKey";
@implementation UIBarButtonItem (BlockSupport)
- (instancetype)initWithTitle:(nullable NSString *)title style:(UIBarButtonItemStyle)style andBlock:(void(^)())clickBlock
{
self = [self initWithTitle:title style:style target:self action:@selector(handleClick)];
if (self) {
objc_setAssociatedObject(self, barbuttonItemBlockKey, clickBlock, OBJC_ASSOCIATION_COPY);
}
return self;
}
- (void)handleClick
{
void (^block)() = objc_getAssociatedObject(self, barbuttonItemBlockKey);
if (block ) {
block();
}
}
@end
.m实现是将外界传进来的clickBlock跟self进行关联
objc_setAssociatedObject(self, barbuttonItemBlockKey, clickBlock,
当点击Item对象的时候,执行handClick方法,在handClick方法通过self拿到外界传递进来的Block,并执行
void (^block)() = objc_getAssociatedObject(self, barbuttonItemBlockKey);
if (block ) {
block();
}
下面使用我们经常处理按钮点击的常用方法来使用objc_setAssociatedObject实现
1.创建一个UIButton的分类
#import <UIKit/UIKit.h>
@interface UIButton (Block)
- (void)addBlock:(void(^)())clickBlock;
@end
#import "UIButton+Block.h"
#import <objc/runtime.h>
const char *buttonBlockKey = "buttonBlockKey";
@implementation UIButton (Block)
- (void)addBlock:(void(^)())clickBlock
{
[self addTarget:self action:@selector(handleClick) forControlEvents:UIControlEventTouchUpInside];
objc_setAssociatedObject(self, buttonBlockKey, clickBlock, OBJC_ASSOCIATION_COPY);
}
- (void)handleClick
{
void (^block)() = objc_getAssociatedObject(self, buttonBlockKey);
if (block ) {
block();
}
}
@end
那么我们在代码中监听按钮的点击事件
[btn addBlock:^{
// 当按钮被点击执行的代码
NSLog(@"-------");
}];
网友评论