mark
runtime在类别category中增加属性的简单方法;
UIView的tap事件快速获取;
UIButton的touchUpInside事件快速获取;
优点是方便快捷,缺点是需要注意block的使用;
内容简单实用,,,仅供初学者参考。。。
#import "UIView+DKView.h"
.h
//
// UIView+DKView.h
// DEMOKING
//
// Created by 王亚振 on 2021/4/25.
//
#import <UIKit/UIKit.h>
typedef void (^DKTapBlock)(void);
@interface UIView (DKView)
/// 调用tapBlock简单的单击事件回调
@property (copy, nonatomic) DKTapBlock tapBlock;
@end
.m
//
// UIView+DKView.m
// DEMOKING
//
// Created by 王亚振 on 2021/4/25.
//
#import "UIView+DKView.h"
#import <objc/runtime.h>
static char kDKTapBlock;
@implementation UIView (DKView)
/// runtime构建属性
/// @param tapBlock 点击回调
- (void)setTapBlock:(DKTapBlock)tapBlock {
// OBJC_ASSOCIATION_COPY 的选取根据属性选择不同的类型
objc_setAssociatedObject(self, &kDKTapBlock, tapBlock, OBJC_ASSOCIATION_COPY);
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMethod:)];
[self addGestureRecognizer:tap];
}
- (DKTapBlock)tapBlock {
return objc_getAssociatedObject(self, &kDKTapBlock);
}
- (void)tapMethod:(UIGestureRecognizer *)tap {
if (self.tapBlock) {
self.tapBlock();
}
}
@end
#import "UIButton+DKButton.h"
.h
//
// UIButton+DKButton.h
// DEMOKING
//
// Created by 王亚振 on 2021/4/25.
//
#import <UIKit/UIKit.h>
typedef void (^DKTouchBlock)(void);
@interface UIButton (DKButton)
/// 调用tapBlock简单的单击事件回调
@property (copy, nonatomic) DKTouchBlock touchBlock;
@end
.m
//
// UIButton+DKButton.m
// DEMOKING
//
// Created by 王亚振 on 2021/4/25.
//
#import "UIButton+DKButton.h"
#import <objc/runtime.h>
static char kDKTouchBlock;
@implementation UIButton (DKButton)
/// runtime构建属性
/// @param touchBlock 点击回调
- (void)setTouchBlock:(DKTouchBlock)touchBlock {
objc_setAssociatedObject(self, &kDKTouchBlock, touchBlock, OBJC_ASSOCIATION_COPY);
[self addTarget:self
action:@selector(touchMethod)
forControlEvents:UIControlEventTouchUpInside];
}
- (DKTouchBlock)touchBlock {
return objc_getAssociatedObject(self, &kDKTouchBlock);
}
- (void)touchMethod {
if (self.touchBlock) {
self.touchBlock();
}
}
@end
使用方法
self.view.tapBlock = ^{
NSLog(@"这里点击了view");
};
self.test2.touchBlock = ^{
NSLog(@"这里点击了button");
};
V动动手指(woai1101992)点个赞吧X