Swift防止按钮重复点击实现+Swift如何运用Runtime
做过OC开发的都知道,我们想要给一个系统的类添加一个属性我们有几种方法,比如继承,我们创建一个父类,给父类写一个属性,之后所有使用的类都采用继承该父类的方式,这样就会都拥有该属性.更高级一点的我们会用到OC的Runtime的机制,
给分类添加属性,即使用 Runtime 中的 objc_setAssociatedObject 和 objc_getAssociatedObject
此外,我们还经常使用方法交换Method Swizzling,对一个既有的类进行方法交换,从而完成一些本来不能完成的事情,比如在viewDidAppear:方法调用的时候想要打印该类,我们通常就会采用方法交换的方式
比如我之前有写一个防止按钮重复点击的分类
之前是这么写的
#import <UIKit/UIKit.h>
#ifndef xlx_defaultInterval
#define xlx_defaultInterval 0.5 //默认时间间隔
#endif
@interface UIButton (Interval)
@property (nonatomic, assign) NSTimeInterval customInterval;//自定义时间间隔
@property (nonatomic, assign) BOOL ignoreInterval;//是否忽略间隔(采用系统默认)
@end
#import "UIButton+Interval.h"
#import <objc/runtime.h>
@implementation UIButton (Interval)
static const char *xlx_customInterval = "xlx_customInterval";
- (NSTimeInterval)customInterval {
return [objc_getAssociatedObject(self, xlx_customInterval) doubleValue];
}
- (void)setCustomInterval:(NSTimeInterval)customInterval {
objc_setAssociatedObject(self, xlx_customInterval, @(customInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
static const char *xlx_ignoreInterval = "xlx_ignoreInterval";
-(BOOL)ignoreInterval {
return [objc_getAssociatedObject(self, xlx_ignoreInterval) integerValue];
}
-(void)setIgnoreInterval:(BOOL)ignoreInterval {
objc_setAssociatedObject(self, xlx_ignoreInterval, @(ignoreInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
+ (void)load{
if ([NSStringFromClass(self.class) isEqualToString:@"UIButton"]) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL systemSel = @selector(sendAction:to:forEvent:);
SEL swizzSel = @selector(mySendAction:to:forEvent:);
Method systemMethod = class_getInstanceMethod([self class], systemSel);
Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
if (isAdd) {
class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
}else{
method_exchangeImplementations(systemMethod, swizzMethod);
}
});
}
}
- (void)mySendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
if (!self