美文网首页
Swift中利用Runtime解决UIButton重复点击的问题

Swift中利用Runtime解决UIButton重复点击的问题

作者: 李先生的咸柠七 | 来源:发表于2019-03-01 19:33 被阅读0次
解决UIButton重复点击问题时主要用到了Runtime中的关联对象(Associated Objects)和方法交叉(Method Swizzling)。

Associated Objects

在解决UIButton重复点击问题时,首先我们需要两个变量,一个是点击的间隔时间,另一个是是否需要忽视点击事件的Bool值,那么我们就需要将这两个变量与UIButton关联起来。

extension UIButton {

private struct AssociatedKeys {
    static var clickDurationTime = "my_clickDurationTime"
    static var isIgnoreEvent = "my_isIgnoreEvent"
}
var defaultDuration : TimeInterval {
    get {
        return 1
    }
}

var clickDurationTime : TimeInterval {
    set {
        objc_setAssociatedObject(self, &AssociateKeys.clickDurationTime, newValue as TimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    
    get {
        if let clickDurationTime = objc_getAssociatedObject(self, &AssociateKeys.clickDurationTime) as? TimeInterval {
            return clickDurationTime
        }
        return defaultDuration
    }
    
}

var isIgnoreEvent: Bool {
    set {
        objc_setAssociatedObject(self, &AssociateKeys.isIgnoreEvent, newValue as Bool, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    get {
        if let isIgnoreEvent = objc_getAssociatedObject(self, &AssociateKeys.isIgnoreEvent) as? Bool {
            return isIgnoreEvent
        }
        return false
    }

}

Method Swizzling

接下来我们需要写一个用来替换UIButton点击事件的方法,在这个方法里来处理重复点击的问题。UIButton继承自UIControl,在传递点击事件是会触发这个方法:

public func sendAction(action: Selector, to target: AnyObject?, forEvent event: UIEvent?)

于是我们重写用来交叉的方法:

  //重写的方法:
@objc func my_sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
    
    if self.isKind(of: UIButton.self) {

        clickDurationTime = clickDurationTime == 0 ? defaultDuration : clickDurationTime
        if isIgnoreEvent {
            return
        } else if clickDurationTime > 0 {
            isIgnoreEvent = true
            // 在过了我们设置的duration之后,再将isIgnoreEvent置为false
            DispatchQueue.main.asyncAfter(deadline: .now() + clickDurationTime) {
                self.isIgnoreEvent = false
            }
            
            my_sendAction(action, to: target, for: event)
            
        } else {
            my_sendAction(action, to: target, for: event)
        }
    }
}
接下来,就是用我们自己重写的SwizzeldMethod来替换UIButton的OriginalMethod:
public class func initializeSendMethod() {
    if self != UIButton.self {
        return
    }
    
    let orSel = #selector(UIButton.sendAction(_:to:for:))
    let swSel = #selector(UIButton.my_sendAction(_:to:for:))
    let orMethod = class_getInstanceMethod(self, orSel)
    let swMethod = class_getInstanceMethod(self, swSel)
    let didAddMethod : Bool = class_addMethod(self, orSel, method_getImplementation(swMethod!), method_getTypeEncoding(swMethod!))
    if didAddMethod {
        class_replaceMethod(self, swSel, method_getImplementation(orMethod!), method_getTypeEncoding(orMethod!))
    } else {
        method_exchangeImplementations(orMethod!, swMethod!)
    }
    
    
}
这个方法,就是在运行时将UIButton的sendAction(:to:forEvent:)替换为我们自己写的my_sendAction(:to:forEvent:)。
在delegate执行        UIButton.initializeSendMethod()

完美!

在 Swift 中 load 类方法永远不会被 runtime 调用,因此在+load方法中实现交叉就变成了不可能的事。出于安全性和一致性的考虑,我们必须确保相关的方法交叉在一个 dispatch_once 中,这样也是很安全的。还有一种方法,在 app delegate 中实现方法交叉, 不像上面通过类扩展进行方法交叉,而是简单地在 app delegate 的 application(_:didFinishLaunchingWithOptions:) 方法调用时中执行相关代码也是可以的。基于对类的修改,这种方法应该就足够确保这些代码会被执行到。

相关文章

网友评论

      本文标题:Swift中利用Runtime解决UIButton重复点击的问题

      本文链接:https://www.haomeiwen.com/subject/yacjuqtx.html