Runtime 实现 动态添加属性

利用动态加载为对象添加一个 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
上一篇:浙江工商大学15年校赛C题 我删我删,删删删 【简单模拟】


下一篇:MySQL 服务安装及命令使用