标签:timeInterval TimeInterval self iOS isIgnoreEvent 点击 UIButton 按钮 btn
UIButton+TimeInterval.h
#import <UIKit/UIKit.h>
@interface UIButton (TimeInterval)
/** 点击时间间隔: 单位(秒) */
@property (nonatomic, assign) NSTimeInterval timeInterval;
@end
UIButton+TimeInterval.m
#import "UIButton+TimeInterval.h"
#import <objc/runtime.h>
@interface UIButton ()
/** 是否忽略响应事件 */
@property(nonatomic, assign) BOOL isIgnoreEvent;
@end
@implementation UIButton (TimeInterval)
/**
应用启动时,hook住所有按钮的event
*/
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL selA = @selector(sendAction:to:forEvent:);
SEL selB = @selector(mySendAction:to:forEvent:);
Method methodA = class_getInstanceMethod(self,selA);
Method methodB = class_getInstanceMethod(self, selB);
BOOL isAdd = class_addMethod(self, selA, method_getImplementation(methodB), method_getTypeEncoding(methodB));
if (isAdd) {
class_replaceMethod(self, selB, method_getImplementation(methodA), method_getTypeEncoding(methodA));
}
else {
method_exchangeImplementations(methodA, methodB);
}
});
}
- (void)mySendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
if ([NSStringFromClass(self.class) isEqualToString:@"UIButton"]) {
if (self.isIgnoreEvent) {
return;
}
if (self.timeInterval > 0) {
self.isIgnoreEvent = YES;
[self performSelector:@selector(setIsIgnoreEvent:) withObject:@(NO) afterDelay:self.timeInterval];
}
}
[self mySendAction:action to:target forEvent:event];
}
// MARK: - 运行时设置分类属性
- (NSTimeInterval)timeInterval {
return [objc_getAssociatedObject(self, _cmd) doubleValue];
}
- (void)setTimeInterval:(NSTimeInterval)timeInterval {
objc_setAssociatedObject(self, @selector(timeInterval), @(timeInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)isIgnoreEvent {
return [objc_getAssociatedObject(self, _cmd) boolValue];
}
- (void)setIsIgnoreEvent:(BOOL)isIgnoreEvent {
objc_setAssociatedObject(self, @selector(isIgnoreEvent), @(isIgnoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
测试
#import "ViewController.h"
#import "UIButton+TimeInterval.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [[UIButton alloc] init];
[self.view addSubview:btn];
[btn setTitle:@"点我" forState:UIControlStateNormal];
[btn sizeToFit];
btn.center = self.view.center;
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
// 关键属性,设置每隔多少秒按钮可点
btn.timeInterval = 2;
}
- (void)btnClick:(UIButton*)sender{
NSLog(@"xxxxxx");
}
@end
标签:timeInterval,TimeInterval,self,iOS,isIgnoreEvent,点击,UIButton,按钮,btn 来源: https://www.cnblogs.com/CH520/p/15566300.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。