#import "UINavigationBar+Add.h"
#import "NSObject+Add.h"
static const int UI_BAR_BUTTON_ITEM_BLOCK_KEY;
@interface UIBarButtonItemBlockTarget : NSObject
@property (nonatomic, copy) UIBarButtonItemActionBlock block;
- (id)initWithBlock:(UIBarButtonItemActionBlock) block;
- (void)invoke:(id)sender;
@end
@implementation UIBarButtonItemBlockTarget
- (id)initWithBlock:(UIBarButtonItemActionBlock)block// 创建一个Block
{
self = [super init];
if (self)
{
_block = [block copy];
}
return self;
}
- (void)invoke:(id)sender
{
!self.block?:self.block(sender);
}
@end
@implementation UIBarButtonItem (Add)
- (void)setActionBlock:(UIBarButtonItemActionBlock)block
{
if (!block) return;
UIBarButtonItemBlockTarget *target = [[UIBarButtonItemBlockTarget alloc] initWithBlock:block];
// 系统类不允许添加实例变量、使用Runtime来关联
[self setAssociateValue:target withKey:&UI_BAR_BUTTON_ITEM_BLOCK_KEY];
[self setTarget:target];
[self setAction:@selector(invoke:)];
}
- (UIBarButtonItemActionBlock)actionBlock
{
// 系统类不允许添加实例变量、使用Runtime来关联
UIBarButtonItemBlockTarget *target = [self getAssociatedValueForKey:&UI_BAR_BUTTON_ITEM_BLOCK_KEY];
return target.block;
}
+ (UIBarButtonItem *)barButtonItemWithTarget:(id)target
Action:(SEL)action
image:(NSString *)image
HighlightedImage:(NSString *)highlightedImage
{
UIButton *button = [[UIButton alloc] init];
[button setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:highlightedImage] forState:UIControlStateHighlighted];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
button.size = button.currentImage.size; // 避免图片拉伸
return [[UIBarButtonItem alloc] initWithCustomView:button];
}
/**
* @param image 默认图片
* @param highlightedImage 高亮状态图片
* @param actionBlock 回调block
*
* @return barButtonItem
*/
+ (UIBarButtonItem *)barButtonItemWithImage:(NSString *)image highlightedImage:(NSString *)highlightedImage actionBlock:(UIBarButtonItemActionBlock)actionBlock
{
UIBarButtonItem *barButtonItem = [UIBarButtonItem barButtonItemWithTarget:nil
Action:nil
image:image
HighlightedImage:highlightedImage];
if (actionBlock)
{
[barButtonItem setActionBlock:actionBlock];
}
return barButtonItem;
}
/**
* @param image 默认图片
* @param highlightedImage 高亮状态图片
* @param actionBlock 回调block
*
* @return barButtonItem
*/
+ (UIBarButtonItem *)barButtonItemWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style actionBlock:(UIBarButtonItemActionBlock)actionBlock
{
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:title style:style target:nil action:nil];
if (actionBlock)
{
[barButtonItem setActionBlock:actionBlock];
}
return barButtonItem;
}
@end
这样做虽然复杂点,但是代码聚合起来更加方便清晰,难点:系统类不允许添加实例变量
所以使用runtime来关联属性
这样写就像:如果afnetworking不是以块,而是以代理的方式来做,会很麻烦
使用方法:这样关联创建和点击事件
self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"Scroll" style:UIBarButtonItemStyleDone actionBlock:^(id sender) {
NSLog(@"123");
}];