Runtime 实现 动态添加属性

时间:2021-09-02 22:48:59

利用动态加载为对象添加一个 block 点击属性;

.h 文件

 #import <UIKit/UIKit.h>

 @interface UIView (Tap)
/**
* 动态添加手势
*/
- (void)setTapActionWithBlock:(void (^)(void))block ;
@end

.m 文件

 #import "UIView+Tap.h"
#import <objc/runtime.h>
/**
* 动态添加手势
*/
static const char *ActionHandlerTapGestureKey; @implementation UIView (Tap) - (void)setTapActionWithBlock:(void (^)(void))block { self.userInteractionEnabled = YES; UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &ActionHandlerTapGestureKey); if (!gesture) {
gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
[self addGestureRecognizer:gesture];
objc_setAssociatedObject(self, &ActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
} objc_setAssociatedObject(self, &ActionHandlerTapGestureKey, block, OBJC_ASSOCIATION_COPY);
} - (void)handleActionForTapGesture:(UITapGestureRecognizer *)gesture {
if (gesture.state == UIGestureRecognizerStateRecognized) {
void(^action)(void) = objc_getAssociatedObject(self, &ActionHandlerTapGestureKey);
if (action) {
action();
}
}
}
@end