Latest 0.0.1
Homepage https://github.com/roycms/delayButton
License MIT
Platforms ios 7.0
Authors

runtimeBtn

最近运用runtime知识写了一个UIButton的分类,实现了按钮每隔2S响应用户点击。效果如下(可以看到每次响应间隔为2s):

效果

核心代码如下:


- (void)swizzle_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    self.interval = self.interval <= 0 ? 2 : self.interval;
    BOOL ok = [[NSDate date] timeIntervalSince1970] - self.interval >= self.lastInterval;
    if (ok) {
        self.lastInterval = [[NSDate date] timeIntervalSince1970];
        [self swizzle_sendAction:action to:target forEvent:event];
    }
}

+ (void)load {
    swizzleMethod([self class], @selector(sendAction:to:forEvent:), @selector(swizzle_sendAction:to:forEvent:));
}

void swizzleMethod(Class class, SEL originalSelector, SEL swizzledSelector) {

    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

    BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));

    if (didAddMethod) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

- (void)setInterval:(NSTimeInterval)interval {
    objc_setAssociatedObject(self, intervalKey, @(interval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSTimeInterval)interval {
    return [objc_getAssociatedObject(self, intervalKey) doubleValue];
}
- (void)setLastInterval:(NSTimeInterval)lastInterval {
    objc_setAssociatedObject(self, lastIntervalKey, @(lastInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSTimeInterval)lastInterval {
    return [objc_getAssociatedObject(self, lastIntervalKey) doubleValue];
}

代码中主要用到了给分类添加属性method_swizzling等知识。

博客地址:runtimeBtn

Latest podspec

{
    "name": "delayButton",
    "version": "0.0.1",
    "summary": "delayButton 0.0.1",
    "description": "Runtime button that response touch Every 2 seconds.",
    "homepage": "https://github.com/roycms/delayButton",
    "license": {
        "type": "MIT",
        "file": "LICENSE"
    },
    "authors": {
        "roycms": "[email protected]"
    },
    "source": {
        "git": "https://github.com/roycms/delayButton.git",
        "tag": "0.0.1"
    },
    "source_files": "delayControl/*.*",
    "ios": {
        "frameworks": "UIKit"
    },
    "platforms": {
        "ios": "7.0"
    }
}

Pin It on Pinterest

Share This