美文网首页
UIButton防止多次点击

UIButton防止多次点击

作者: gf_金鱼佬 | 来源:发表于2020-11-27 13:35 被阅读0次

    不多bb,直接上干货

    #import <UIKit/UIKit.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface UIControl (EventInterval)
    
    /// 按钮响应间隔
    @property (nonatomic, assign) NSTimeInterval eventInterval;
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    #import "UIControl+EventInterval.h"
    #import <objc/runtime.h>
    
    static char *const eventIntervalKey = "eventIntervalKey";
    static char *const eventUnavailableKey = "eventUnavailableKey";
    static NSTimeInterval const defaultEventInterval = 0;
    
    @interface UIControl ()
    
    @property (nonatomic, assign) BOOL eventUnavailable;
    
    @end
    
    @implementation UIControl (EventInterval)
    
    + (void)load {
        Method method = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
        Method gf_method = class_getInstanceMethod(self, @selector(gf_sendAction:to:forEvent:));
        method_exchangeImplementations(method, gf_method);
    }
    
    #pragma mark - ActionFun
    - (void)gf_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
        if ([self isKindOfClass:[UIButton class]]) {
            if (self.eventUnavailable == NO) {
                self.eventUnavailable = YES;
                [self gf_sendAction:action to:target forEvent:event];
                [self performSelector:@selector(setEventUnavailable:) withObject:@(NO) afterDelay:self.eventInterval > 0 ? self.eventInterval : defaultEventInterval];
            }
        }
        else{
            [self gf_sendAction:action to:target forEvent:event];
        }
    }
    
    #pragma mark - setter & getter
    - (NSTimeInterval)eventInterval {
        return [objc_getAssociatedObject(self, eventIntervalKey) doubleValue];
    }
    
    - (void)setEventInterval:(NSTimeInterval)eventInterval {
        objc_setAssociatedObject(self, eventIntervalKey, @(eventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    - (BOOL)eventUnavailable {
        return [objc_getAssociatedObject(self, eventUnavailableKey) boolValue];
    }
    
    - (void)setEventUnavailable:(BOOL)eventUnavailable {
        objc_setAssociatedObject(self, eventUnavailableKey, @(eventUnavailable), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:UIButton防止多次点击

          本文链接:https://www.haomeiwen.com/subject/budxwktx.html