UIBarButtonItem+BlocksKit.m 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //
  2. // UIBarButtonItem+BlocksKit.m
  3. // BlocksKit
  4. //
  5. #import <objc/runtime.h>
  6. #import "UIBarButtonItem+BlocksKit.h"
  7. static const void *BKBarButtonItemBlockKey = &BKBarButtonItemBlockKey;
  8. @interface UIBarButtonItem (BlocksKitPrivate)
  9. - (void)bk_handleAction:(UIBarButtonItem *)sender;
  10. @end
  11. @implementation UIBarButtonItem (BlocksKit)
  12. - (id)bk_initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem handler:(void (^)(id sender))action
  13. {
  14. self = [self initWithBarButtonSystemItem:systemItem target:self action:@selector(bk_handleAction:)];
  15. if (!self) return nil;
  16. objc_setAssociatedObject(self, BKBarButtonItemBlockKey, action, OBJC_ASSOCIATION_COPY_NONATOMIC);
  17. return self;
  18. }
  19. - (id)bk_initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style handler:(void (^)(id sender))action
  20. {
  21. self = [self initWithImage:image style:style target:self action:@selector(bk_handleAction:)];
  22. if (!self) return nil;
  23. objc_setAssociatedObject(self, BKBarButtonItemBlockKey, action, OBJC_ASSOCIATION_COPY_NONATOMIC);
  24. return self;
  25. }
  26. - (id)bk_initWithImage:(UIImage *)image landscapeImagePhone:(UIImage *)landscapeImagePhone style:(UIBarButtonItemStyle)style handler:(void (^)(id sender))action
  27. {
  28. self = [self initWithImage:image landscapeImagePhone:landscapeImagePhone style:style target:self action:@selector(bk_handleAction:)];
  29. if (!self) return nil;
  30. objc_setAssociatedObject(self, BKBarButtonItemBlockKey, action, OBJC_ASSOCIATION_COPY_NONATOMIC);
  31. return self;
  32. }
  33. - (id)bk_initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style handler:(void (^)(id sender))action
  34. {
  35. self = [self initWithTitle:title style:style target:self action:@selector(bk_handleAction:)];
  36. if (!self) return nil;
  37. objc_setAssociatedObject(self, BKBarButtonItemBlockKey, action, OBJC_ASSOCIATION_COPY_NONATOMIC);
  38. return self;
  39. }
  40. - (void)bk_handleAction:(UIBarButtonItem *)sender
  41. {
  42. void (^block)(id) = objc_getAssociatedObject(self, BKBarButtonItemBlockKey);
  43. if (block) block(self);
  44. }
  45. @end