swift4 使用黑魔法防止按钮重复点击

2018-08-24  本文已影响182人  灯红酒绿映不出的落寞

要想全局处理防止按钮重复点击,一个很优雅的方法就是利用runtime来在运行时处理点击。

来看一段Mattt Thompson大神(AFNetworking作者之一)的实现

#import <objc/runtime.h>
@implementation UIViewController (Tracking)
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        SEL originalSelector = @selector(viewWillAppear:);
        SEL swizzledSelector = @selector(xxx_viewWillAppear:);
        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);
        }
    });
}
#pragma mark - Method Swizzling
- (void)xxx_viewWillAppear:(BOOL)animated {
    [self xxx_viewWillAppear:animated];
    NSLog(@"viewWillAppear: %@", self);
}
@end

Mattt Thompson大神在他的一篇文章Method Swizzling中提到method swizzling使用的几个要点,其中有2个要点的实现是我们在转换到Swift中可能遇到困难的地方:

  1. swizzling 应该只在 dispatch_once 中完成
  2. swizzling应该只在+load中完成

对于我们现在使用的swift4.x , Xcode9.x 来说, API中已经找不到dispatch_once,+load或者+initialize(),问题来了,如果我们还想继续使用runtime就必须找出对应的swift替代这几个方法

对于dispatch_once来说,swift中static let这样声明的变量其实已经用到dispatch_once了,比如

class SingletonClass  {
    static let sharedInstance = SingletonClass()
}

对于+load或者+initialize() 的替代方法 JORDAN SMITH的文章Handling the Deprecation of initialize()给出了一个解决方案.

protocol SelfAware: class {
    static func awake()
}
class NothingToSeeHere {
    static func harmlessFunction() {
        let typeCount = Int(objc_getClassList(nil, 0))
        let types = UnsafeMutablePointer<AnyClass>.allocate(capacity: typeCount)
        let autoreleasingTypes = AutoreleasingUnsafeMutablePointer<AnyClass>(types)
        objc_getClassList(autoreleasingTypes, Int32(typeCount))
        for index in 0 ..< typeCount {
            (types[index] as? SelfAware.Type)?.awake()
        }
        types.deallocate(capacity: typeCount)
    }
}
extension UIApplication {
    private static let runOnce: Void = {
        NothingToSeeHere.harmlessFunction()
    }()
    override open var next: UIResponder? {
        // Called before applicationDidFinishLaunching
        UIApplication.runOnce
        return super.next
    }
}

JORDAN SMITH想法其实很简单,是通过runtime获取到所有类的列表,然后向所有遵循SelfAware协议的类发送消息,并且他把这些操作放到了UIApplication的next属性的调用中,同时发现了next属性会在applicationDidFinishLaunching之前被调用。

至此我们也还算优雅地解决了+load的问题。

最后

看下如何使用黑魔法防止按钮重复点击,这里我们对UIButton做一个扩展,代码如下

struct RuntimeKey {
    static let zm_eventUnavailable = UnsafeRawPointer.init(bitPattern: "zm_eventUnavailable".hashValue)!
    static let eventInterval = 1.5 // 按钮重复点击间隔
}
import Foundation

protocol SelfAware: class {
    static func awake()
}
class NothingToSeeHere {
    static func harmlessFunction() {
        let typeCount = Int(objc_getClassList(nil, 0))
        let types = UnsafeMutablePointer<AnyClass>.allocate(capacity: typeCount)
        let autoreleasingTypes = AutoreleasingUnsafeMutablePointer<AnyClass>(types)
        objc_getClassList(autoreleasingTypes, Int32(typeCount))
        for index in 0 ..< typeCount {
            (types[index] as? SelfAware.Type)?.awake()
        }
        types.deallocate(capacity: typeCount)
    }
}
extension UIApplication {
    private static let runOnce: Void = {
        NothingToSeeHere.harmlessFunction()
    }()
    override open var next: UIResponder? {
        // Called before applicationDidFinishLaunching
        UIApplication.runOnce
        return super.next
    }
}

extension UIButton: SelfAware {
    static func awake() {
        UIButton.classInit()
    }
    
    static func classInit() {
        swizzleMethod
    }
    
    private static let swizzleMethod: Void = {
        let normalSelector = #selector(UIButton.sendAction(_:to:for:))
        let swizzledSelector = #selector(swizzled_senderAction(_:to:event:))
        let originalMethod = class_getInstanceMethod(UIButton.self, normalSelector)
        let swizzledMethod = class_getInstanceMethod(UIButton.self, swizzledSelector)
        
        guard (originalMethod != nil && swizzledMethod != nil) else {
            return
        }
        
        let isAdd = class_addMethod(UIButton.self, normalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
        
        if isAdd {
            class_replaceMethod(UIButton.self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
        } else {
            method_exchangeImplementations(originalMethod!, swizzledMethod!)
        }
        
    }()
    
    @objc private func swizzled_senderAction(_ action: Selector, to: Any?, event: UIEvent?) {
//        print("警告      我是按钮被点击了")
        if eventUnavailable == nil {
            eventUnavailable = false
        }
        if !eventUnavailable! {
            self.eventUnavailable = true
            swizzled_senderAction(action, to: to, event: event)
            DispatchQueue.main.asyncAfter(deadline: .now() + RuntimeKey.eventInterval, execute: {
                self.eventUnavailable = false
            })
        }
    }
    
    private var eventUnavailable: Bool? {
        set{
            objc_setAssociatedObject(self, RuntimeKey.zm_eventUnavailable, newValue, .OBJC_ASSOCIATION_ASSIGN)
        }
        get{
            return objc_getAssociatedObject(self, RuntimeKey.zm_eventUnavailable) as? Bool
        }
    }
    
}

这样一个简单的方法交换就实现了,我们通过eventUnavailable这个属性同时使用DispatchQueue.main.asyncAfter模拟延迟加载达到我们想要的防止按钮重复点击的效果

你可能想知道的
如何优雅地在Swift4中实现Method Swizzling
Swift 4 Method Swizzling (Part 2/2)

上一篇 下一篇

猜你喜欢

热点阅读