#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIBarButtonItem`.
*/
@interface UIBarButtonItem (YYAdd)
/**
The block that invoked when the item is selected. The objects captured by block
will retained by the ButtonItem.
@discussion This param is conflict with `target` and `action` property.
Set this will set `target` and `action` property to some internal objects.
*/
@property (nullable, nonatomic, copy) void (^actionBlock)(id);
@end
#import "UIBarButtonItem+YYAdd.h"
#import "YYKitMacro.h"
#import <objc/runtime.h>
YYSYNTH_DUMMY_CLASS(UIBarButtonItem_YYAdd)
static const int block_key;
@interface _YYUIBarButtonItemBlockTarget : NSObject
@property (nonatomic, copy) void (^block)(id sender);
- (id)initWithBlock:(void (^)(id sender))block;
- (void)invoke:(id)sender;
@end
@implementation _YYUIBarButtonItemBlockTarget
- (id)initWithBlock:(void (^)(id sender))block{
self = [super init];
if (self) {
_block = [block copy];
}
return self;
}
- (void)invoke:(id)sender {
if (self.block) self.block(sender);
}
@end
@implementation UIBarButtonItem (YYAdd)
- (void)setActionBlock:(void (^)(id sender))block {
_YYUIBarButtonItemBlockTarget *target = [[_YYUIBarButtonItemBlockTarget alloc] initWithBlock:block];
objc_setAssociatedObject(self, &block_key, target, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self setTarget:target];
[self setAction:@selector(invoke:)];
}
- (void (^)(id)) actionBlock {
_YYUIBarButtonItemBlockTarget *target = objc_getAssociatedObject(self, &block_key);
return target.block;
}
@end
利用_YYUIBarButtonItemBlockTarget 中间件给按钮添加block回调
setter方法中 给barbuttonitem 添加一个target与action,用runtime添加属性
getter方法中获取target的block