swift语言 使用method_exchangeImplementations 交换原生方法不行了 ,fuck
今天想做一个小需求,防止UIButton在多时间内多次点击。
import UIKit
private var UIControl_ignoreEvent = "UIControl_ignoreEvent"
extension UIControl {
//添加点击事件的间隔事件
var xh_acceptEventInterval:NSTimeInterval {
get {
let acceptEventInterval = objc_getAssociatedObject(self, #function) as? NSTimeInterval
return acceptEventInterval ?? 0
}
set {
objc_setAssociatedObject(self, #function, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
//是否忽略点击事件,不响应点击事件
func setXh_ignoreEvent(newValue:Bool) {
objc_setAssociatedObject(self, &UIControl_ignoreEvent, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
func xh_ignoreEvent() -> Bool {
let ignoreEvent = objc_getAssociatedObject(self, &UIControl_ignoreEvent) as? Bool
return ignoreEvent ?? false
}
override public class func initialize() {
var onceToken : dispatch_once_t = 0;
dispatch_once(&onceToken) {
let originalSelector = class_getInstanceMethod(self, #selector(UIControl.sendAction(_:to:forEvent:)))
let swizzledSelector = class_getInstanceMethod(self, #selector(UIControl.__xh_sendAction(_:to:forEvent:)))
method_exchangeImplementations(swizzledSelector,originalSelector)
}
}
func __xh_sendAction(action: Selector, to target: AnyObject?, forEvent event: UIEvent?) {
print("走了替换后的方法")
if self.xh_ignoreEvent() {
return
}
if self.xh_acceptEventInterval > 0 {
self.setXh_ignoreEvent(true)
self.performSelector(#selector(setXh_ignoreEvent(_:)), withObject: false, afterDelay: self.xh_acceptEventInterval)
}
self.__xh_sendAction(action, to: target, forEvent: event)
}
}
可惜 swift语言 使用method_exchangeImplementations 交换原生方法不行了
参考:https://stackoverflow.com/questions/33096873/method-swizzling-does-not-work