對於這個功能的實現是看了這個兩個連接裏的內容,主要是爲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;
@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