Swift Swizzle

前端之家收集整理的这篇文章主要介绍了Swift Swizzle前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

注意点:如果不是 NSObject或者其子类,那么需要将 替换方法前 + dynamic 可动态派发

extension UIButton {

@H_403_12@ classfunc Mrshan_swizzleSendAction() {

@H_403_12@ struct xxx_swizzleToken {

@H_403_12@ staticvar onceToken : dispatch_once_t =0

@H_403_12@ }

//设定这个方法只是执行一次,在第一个uibutton初始化的时候执行这个方法,嘻嘻

@H_403_12@ dispatch_once(&xxx_swizzleToken.onceToken) {

@H_403_12@ let cls:AnyClass! = UIButton.self

@H_403_12@ let originalSelector =Selector("sendAction:to:forEvent:")

@H_403_12@ let swizzledSelector =Selector("Mrshan_sendAction:to:forEvent:")

@H_403_12@ let originalMethod =class_getInstanceMethod(cls,originalSelector)

@H_403_12@ let swizzledMethod =class_getInstanceMethod(cls,swizzledSelector)

@H_403_12@

@H_403_12@ method_exchangeImplementations(originalMethod,swizzledMethod)

//在这里进行方法实现的替换,下一个页面中的两个方法的互换

@H_403_12@ let cls1 =twoViewController.self

@H_403_12@ let originSelect1 =Selector("one")

@H_403_12@ let swizzleSelect1 =Selector("two")

@H_403_12@ let originMethod1 =class_getInstanceMethod(cls1,originSelect1)

@H_403_12@ let swizzleMethod1 =class_getInstanceMethod(cls1,swizzleSelect1)

@H_403_12@ method_exchangeImplementations(originMethod1,swizzleMethod1)

@H_403_12@ }

@H_403_12@ }

@H_403_12@ /**

这个是被调换的方法的实现

- parameter action: <#action description#>

- parameter to: <#to description#>

- parameter forEvent: <#forEvent description#>

*/

@H_403_12@ publicfunc Mrshan_sendAction(action: Selector,

@H_403_12@ to: AnyObject!,

@H_403_12@ forEvent: UIEvent!)

@H_403_12@ {

//计数器+=1

xxx_buttonTapCounter.count +=1

print(xxx_buttonTapCounter.count)

//这里并不是调用的自己,因为在执行这个方法的时候,Mrshan_sendAction 和 sendAction 的实现已经调换了,所以执行的是原来的button的点击事件

@H_403_12@ Mrshan_sendAction(action,to: to,forEvent: forEvent)

@H_403_12@ }

@H_403_12@ /**

重写构造方法,并且确认构造者是uibutton

- returns: <#return value description#>

*/

overridepublic classfunc initialize() {

//别用断言。。老实一点用IF

@H_403_12@ ifself != UIButton.self {

@H_403_12@ return

@H_403_12@ }

UIButton.Mrshan_swizzleSendAction()

@H_403_12@ }

@H_403_12@}


/**

* button的点击计数器

*/

@H_403_12@struct xxx_buttonTapCounter {

@H_403_12@ staticvar count: Int =0

@H_403_12@}

原文链接:https://www.f2er.com/swift/324638.html

猜你在找的Swift相关文章