天天看點

iOS 基于runtime 解決UIButton重複點選 發送多次請求問題

這裡使用的是Runtime的黑魔法方法實作,靈感來源于CocoChina,在用網上搜到的方法運作不成功,死循環,廢話不多說上自己的代碼。

給UIControl建個類目

UIControl+FMGControl.h

#import <UIKit/UIKit.h>
@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
           

使用方法:

在需要用到的地方導入頭檔案

給按鈕設定間隔時間 self.acceptEventInterval 同時不會影響到導覽列上的按鈕

原文位址:http://www.jianshu.com/p/c42720d29986