Last active
April 21, 2020 08:33
-
-
Save kashiftriffort/cc642a53d7fff483f42bc10f59fdf4cf to your computer and use it in GitHub Desktop.
Intercept Action Swizzling in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@objc static func swizzleMethod() { | |
guard self == UIApplication.self else { | |
return | |
} | |
let sendActionSelector = #selector(self.sendAction(_:to:from:for:)) | |
let swizzleActionSelector = #selector(self.interceptAction(_:to:from:for:)) | |
let sendActionMethod = class_getInstanceMethod(self, sendActionSelector) | |
let swizzleActionMethod = class_getInstanceMethod(self, swizzleActionSelector) | |
method_exchangeImplementations(sendActionMethod!, swizzleActionMethod!) | |
} | |
@objc func interceptAction(_ action: Selector, | |
to target: Any?, | |
from sender: Any?, | |
for event: UIEvent?) -> Bool { | |
DispatchQueue.main.async { | |
self.captureSenderInfo(sender: sender) | |
} | |
return self.interceptAction(action, to: target, from: sender, for: event) | |
} | |
internal func captureSenderInfo(sender: Any?) { | |
if let button = sender as? UIButton { | |
logButton(T: button) | |
} else if let barButton = sender as? UIBarButtonItem { | |
logBarButton(T: barButton) | |
} else if let pageControl = sender as? UIPageControl { | |
logPageControl(T: pageControl) | |
} | |
} | |
func logButton<T>(T: T) where T: UIButton { | |
print(T.currentTitle) | |
} | |
func logBarButton<T>(T: T) where T: UIBarButtonItem { | |
print(T.title) | |
} | |
func logPageControl<T>(T: T) where T: UIPageControl { | |
print(T.currentPage) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment