Swift :
@objc public extension UIGestureRecognizer{
private struct AssociateKeys {
static var funcName = "UIGestureRecognizer" + "funcName"
static var closure = "UIGestureRecognizer" + "closure"
}
/// 闭包回调
func addAction(_ closure: @escaping (UIGestureRecognizer) -> Void) {
objc_setAssociatedObject(self, &AssociateKeys.closure, closure, .OBJC_ASSOCIATION_COPY_NONATOMIC);
addTarget(self, action: #selector(p_invoke))
}
private func p_invoke() {
if let closure = objc_getAssociatedObject(self, &AssociateKeys.closure) as? ((UIGestureRecognizer) -> Void) {
closure(self);
}
}
}
OC :
#import "UIGestureRecognizer+Helper.h"
- (void)addActionBlock:(void(^)(UIGestureRecognizer *reco))block {
if (!block) {
return;
}
objc_setAssociatedObject(self, _cmd, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(p_invoke:)];
}
- (void)p_invoke:(UIGestureRecognizer *)sender {
void(^block)(UIGestureRecognizer *reco) = objc_getAssociatedObject(self, @selector(addActionBlock:));
if (block) {
block(sender);
}
}
#import "UIBarButtonItem+Helper.h"
- (void)addActionBlock:(void (^)(UIBarButtonItem *item))block{
if (block) {
objc_setAssociatedObject(self, @selector(actionBlock), block, OBJC_ASSOCIATION_COPY);
// Sets up the action.
self.target = self;
self.action = @selector(p_invoke);
}
}
- (void)p_invoke {
void(^block)(UIBarButtonItem *item) = objc_getAssociatedObject(self, @selector(addActionBlock:));
if (block) {
block(self);
}
}
网友评论