Swift Swizzle
注意点:如果不是 NSObject或者其子类,那么需要将 替换方法前 + dynamic 可动态派发 extension UIButton { classfunc Mrshan_swizzleSendAction() { struct xxx_swizzleToken { staticvar onceToken : dispatch_once_t =0 } //设定这个方法只是执行一次,在第一个uibutton初始化的时候执行这个方法,嘻嘻 dispatch_once(&xxx_swizzleToken.onceToken) { let cls:AnyClass! = UIButton.self let originalSelector =Selector("sendAction:to:forEvent:") let swizzledSelector =Selector("Mrshan_sendAction:to:forEvent:") let originalMethod =class_getInstanceMethod(cls,originalSelector) let swizzledMethod =class_getInstanceMethod(cls,swizzledSelector)
method_exchangeImplementations(originalMethod,swizzledMethod) //在这里进行方法实现的替换,下一个页面中的两个方法的互换 let cls1 =twoViewController.self let originSelect1 =Selector("one") let swizzleSelect1 =Selector("two") let originMethod1 =class_getInstanceMethod(cls1,originSelect1) let swizzleMethod1 =class_getInstanceMethod(cls1,swizzleSelect1)
method_exchangeImplementations(originMethod1,swizzleMethod1) } }
/** 这个是被调换的方法的实现
- parameter action: <#action description#> - parameter to: <#to description#> - parameter forEvent: <#forEvent description#> */ publicfunc Mrshan_sendAction(action: Selector, to: AnyObject!, forEvent: UIEvent!) { //计数器+=1 xxx_buttonTapCounter.count +=1 print(xxx_buttonTapCounter.count) //这里并不是调用的自己,因为在执行这个方法的时候,Mrshan_sendAction 和 sendAction 的实现已经调换了,所以执行的是原来的button的点击事件 Mrshan_sendAction(action,to: to,forEvent: forEvent) }
/** 重写构造方法,并且确认构造者是uibutton
- returns: <#return value description#> */ overridepublic classfunc initialize() { //别用断言。。老实一点用IF ifself != UIButton.self { return } UIButton.Mrshan_swizzleSendAction() } }
/** * button的点击计数器 */ struct xxx_buttonTapCounter { staticvar count: Int =0 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |