ios button重複點擊問題

#import "UIControl+Extension.h"
#import <objc/runtime.h>

static const char *UIControl_acceptEventInterval = "UIControl_resumeEventInterval";
static const void *BandNameKey = &BandNameKey;


@implementation UIControl (Extension)

# pragma mark - set get
- (void)setResumeEventInterval:(NSTimeInterval)resumeEventInterval
{
    objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(resumeEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSTimeInterval)resumeEventInterval
{
    return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];
}


- (void)setIgnoreEvent:(BOOL)ignoreEvent
{
    
    objc_setAssociatedObject(self, BandNameKey, [NSNumber numberWithBool:ignoreEvent], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)ignoreEvent
{
    
    return [objc_getAssociatedObject(self, BandNameKey) boolValue];
}

#pragma mark -延時執行
+ (void)load
{
    
    SEL oldSelector = @selector(sendAction:to:forEvent:);
    SEL newSelector = @selector(__resume_sendAction:to:forEvent:);
    
    Method oldMethod = class_getInstanceMethod(self, oldSelector);
    Method newMethod = class_getInstanceMethod(self, newSelector);
    
    
    if (class_addMethod(self,
                        oldSelector,
                        method_getImplementation(newMethod),
                        method_getTypeEncoding(newMethod))) {
        class_replaceMethod(self,
                            newSelector,
                            method_getImplementation(oldMethod),
                            method_getTypeEncoding(oldMethod));
    } else {
        method_exchangeImplementations(oldMethod, newMethod);
    }
}
- (void)__resume_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{
    if (self.ignoreEvent){
        return;
    }
    if (self.resumeEventInterval > 0){
        self.ignoreEvent = YES;
        //GCD多線程延時執行
        dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.resumeEventInterval * NSEC_PER_SEC));
        dispatch_after(time, dispatch_get_main_queue(), ^{
            self.ignoreEvent = NO;
        });
    }
    [self __resume_sendAction:action to:target forEvent:event];
}

 

使用

UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [addButton setTitle:@"保存" forState:UIControlStateNormal];
    
     addButton.resumeEventInterval = 2.0;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章