一、当通过点击按钮来执行网络请求时,若请求耗时稍长,用户往往会再点一次。这样,就执行了两次请求,造成了资源浪费。通过Runtime控制UIButton响应事件的时间间隔。
1、创建UIButton的分类
.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIButton (YMEventInterval)
#pragma mark- 设置间隔时间
@property (nonatomic,assign)NSTimeInterval eventInterval;
@end
NS_ASSUME_NONNULL_END
.m
#import "UIButton+YMEventInterval.h"
#import <objc/message.h>
@interface UIButton()
@property (nonatomic,assign)BOOL eventUnavailable;
@end
@implementation UIButton (YMEventInterval)
+(void)load
{
//方法交换
Method method=class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
Method ymMethod=class_getInstanceMethod(self, @selector(ymSendAction:to:forEvent:));
method_exchangeImplementations(method, ymMethod);
}
-(void)setEventInterval:(NSTimeInterval)eventInterval
{
objc_setAssociatedObject(self, "eventIntervalKey", @(eventInterval), OBJC_ASSOCIATION_ASSIGN);
}
-(NSTimeInterval)eventInterval
{
return [objc_getAssociatedObject(self, "eventIntervalKey") doubleValue];
}
-(void)setEventUnavailable:(BOOL)eventUnavailable
{
objc_setAssociatedObject(self, "eventUnavailableKey", @(eventUnavailable), OBJC_ASSOCIATION_ASSIGN);
}
-(BOOL)eventUnavailable
{
return [objc_getAssociatedObject(self, "eventUnavailableKey") boolValue];
}
- (void)ymSendAction:(SEL)action to:(nullable id)target forEvent:(nullable UIEvent *)event
{
if (self.eventUnavailable==NO) {
self.eventUnavailable=YES;
[self ymSendAction:action to:target forEvent:event];
[self performSelector:@selector(setEventUnavailable:) withObject:@(NO) afterDelay:self.eventInterval];
}
}
@end
使用
self.btn2=[UIButton buttonWithType:UIButtonTypeCustom];
self.btn2.frame=CGRectMake(20, 200, 300, 40);
self.btn2.backgroundColor=[UIColor orangeColor];
[self.view addSubview:self.btn2];
[self.btn2 addTarget:self action:@selector(click2) forControlEvents:UIControlEventTouchUpInside];
//设置间隔
self.btn2.eventInterval=3;