解决UIButton重复点击,发送多次请求问题

这里使用的是Runtime的黑魔法方法实现,灵感来源于CocoChina,在用网上搜到的方法运行不成功,死循环,废话不多说上自己的代码。

给UIControl建个分类
UIControl+FMGControl.h

#import 
@interface UIControl (FMGControl)
/** 按钮点击间隔*/
@property (assign, nonatomic) NSTimeInterval acceptEventInterval;

@end

UIControl+FMGControl.m

 
#import "UIControl+FMGControl.h"

static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval";

@implementation UIControl (FMGControl)

- (NSTimeInterval)acceptEventInterval
{
    return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];
}


- (void)setAcceptEventInterval:(NSTimeInterval)acceptEventInterval
{
    objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)FMG_ignoreEvent
{
    return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];
}


+ (void)load
{
    Method a = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    Method b = class_getInstanceMethod(self, @selector(FMG_sendAction:to:froEvent:));
    
    method_exchangeImplementations(a, b);
}

- (void)FMG_sendAction:(SEL)action to:(id)target froEvent:(UIEvent *)event
{
    if (self.acceptEventInterval > 0) {
        if (self.userInteractionEnabled) {
            
            [self FMG_sendAction:action to:target froEvent:event];
        }
        self.userInteractionEnabled = NO;
        
        [self performSelector:@selector(setUserInteractionEnabled:) withObject:@(YES) afterDelay:self.acceptEventInterval];


        /* GCD 延迟执行 self.acceptEventInterval:为延迟时间
        __weak typeof (self) weakSelf = self;
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.acceptEventInterval * NSEC_PER_SEC));
        
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            weakSelf.userInteractionEnabled = YES;
        });
        
        */
    
    } else {
        [self FMG_sendAction:action to:target froEvent:event];
    }
    
}

@end

使用:

在你需要用到的地方导入头文件: UIControl+FMGControl.h
用到的地方多的话,可以导入到pch 文件中
然后给按钮设置个间隔时间 self.acceptEventInterval

同时不会影响到导航条上的按钮

你可能感兴趣的:(解决UIButton重复点击,发送多次请求问题)