ios解決button重複點擊的問題

分類頭文件:ide

#import <UIKit/UIKit.h>atom

 

@interface UIControl (CDControlCategory)spa

@property(nonatomic,assign)NSTimeInterval uxy_acceptEventInterval;// 能夠用這個給重複點擊加間隔3d

@property (nonatomic) BOOL ignoreEvent;orm

@end對象

 

 

----------分類實現:----------ci

#import "UIControl+HCDControlCategory.h"get

#import <objc/runtime.h>it

 

static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval";io

static const char *UIControl_ignoreEvent = "UIControl_ignoreEvent";

 

 

@implementation UIControl (HCDControlCategory)

 

//改變兩個方法的實現。在類第一次使用的時候回調用這個方法

+(void)load{

    Method a = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));

    Method b = class_getInstanceMethod(self, @selector(__uxy_sendAction:to:forEvent:));

    //改變兩個方法的實現

    method_exchangeImplementations(a, b);

}

//經過關聯對象重寫getset方法

- (NSTimeInterval)uxy_acceptEventInterval

{

    return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];

}

 

- (void)setUxy_acceptEventInterval:(NSTimeInterval)uxy_acceptEventInterval

{

    objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(uxy_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

#pragma mark 如今是否可點的getset。經過關聯對象。

-(void)setIgnoreEvent:(BOOL)ignoreEvent{

    objc_setAssociatedObject(self, UIControl_ignoreEvent, @(ignoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

-(BOOL)ignoreEvent{

    return [objc_getAssociatedObject(self, UIControl_ignoreEvent) boolValue];

}

 

 

- (void)__uxy_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event

{

    if (self.ignoreEvent) return;

    if (self.uxy_acceptEventInterval > 0)

    {

        

        self.ignoreEvent = YES;

        [self performSelector:@selector(setIgnoreEvent:) withObject:@(NO) afterDelay:self.uxy_acceptEventInterval];

    }

    //調用系統實現

    [self __uxy_sendAction:action to:target forEvent:event];

}

 

 

@end

 

 

------------------ 使用 ---------------

- (void)viewDidLoad {

    [super viewDidLoad];

 

    UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    tempBtn.frame = CGRectMake(100, 100, 30, 30);

    tempBtn.backgroundColor = [UIColor greenColor];

    [tempBtn addTarget:self action:@selector(clickWithInterval:) forControlEvents:UIControlEventTouchUpInside];

    tempBtn.uxy_acceptEventInterval = 2.5;

    

    [self.view addSubview:tempBtn];

}

 

 

#pragma mark 這裏其實就是調用咱們自定義的那個方法。

-(void)clickWithInterval:(UIButton *)sender{

    NSLog(@"你試試看。");

}

相關文章
相關標籤/搜索