用RunTime来防止按钮被多次点击

对于这个功能的实现是看了这个两个连接里的内容,主要是为UIButton增加一个延时的属性。

1、http://www.cocoachina.com/ios/20150911/13260.html

2、http://blog.sina.com.cn/s/blog_60342e330101tcz1.html

我这边总共做了两个,一个是创建UIButton的子类来实现,另一个是创建UIButton的cateorgy来实现。


第一个,创建UIButton的子类来实现

@interface MyButton :UIButton

@property (assign,nonatomic)NSTimeInterval timeInterval;

@end


@interface MyButton()

@property (assign,nonatomic)BOOL ignoreEvent;

@end

@implementation MyButton


+(void)load

{

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

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

    //是将a方法替换成b方法

    method_exchangeImplementations(a, b);

}


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

{

    //如果是YES,规定的延时还没到

    if (self.ignoreEvent) {

       return;

    }

    

   if (self.timeInterval >0) {

        //先设置这个参数为YES

       self.ignoreEvent =YES;

        //当指定延时时间到后,再将这个参数设为NO

        [selfperformSelector:@selector(setIgnoreEvent:)withObject:@(NO)afterDelay:self.timeInterval];

    }

    

    [selftimer_sendAction:actionto:target forEvent:event];

}


在按钮使用界面

[self.buttonaddTarget:selfaction:@selector(click:)forControlEvents:UIControlEventTouchUpInside];

//设置延时时间,单位秒

self.button.timeInterval =5;


第二个,创建UIButton的cateorgy来实现

由于category不能扩展属性,所以,必须用objc_setAssociatedObject和objc_getAssociatedObject来设置和关联属性

@interface UIButton (ZM)

//设置延时时间

@property (assign,nonatomic)NSTimeInterval timeInterval;


@end


@implementation UIButton (ZM)

@dynamic timeInterval;


//是否可以再次点击 0代表未被点击 1代表已被点击

static BOOL isClick;


+(void)load

{

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

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

    method_exchangeImplementations(a, b);

}


-(NSTimeInterval)timeInterval

{

    return [objc_getAssociatedObject(self, @selector(timeInterval)) doubleValue];

}


-(void)setTimeInterval:(NSTimeInterval)timeInterval

{

    //第二个参数key,用@selector是因为SEL生成的时候就是一个唯一的常量

    objc_setAssociatedObject(self, @selector(timeInterval), @(timeInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}


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

{

    if (isClick) {

        return;

    }

    

    if (self.timeInterval > 0) {

        isClick = YES;

        

        //当指定延时时间到后,再将这个参数设为NO

        [self performSelector:@selector(setIsClick:) withObject:@(NO) afterDelay:self.timeInterval];

    }

    

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

}


-(void)setIsClick:(BOOL)flag

{

    isClick = flag;

}


@end



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值