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

来源:互联网 发布:手机可以恢复u盘数据吗 编辑:程序博客网 时间:2024/05/18 18:19

对于这个功能的实现是看了这个两个连接里的内容,主要是为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:targetforEvent: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代表已被点击

staticBOOL 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

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

    }

    

    [selftimer_sendAction:action to:target forEvent:event];

}


-(void)setIsClick:(BOOL)flag

{

   isClick = flag;

}


@end



0 0
原创粉丝点击