Skip to content

Instantly share code, notes, and snippets.

@Pulichev
Last active August 29, 2019 08:56
Show Gist options
  • Save Pulichev/9709120149c66cce1c9cfc34c3ec194e to your computer and use it in GitHub Desktop.
Save Pulichev/9709120149c66cce1c9cfc34c3ec194e to your computer and use it in GitHub Desktop.
UIViewController viewDidLoad swizzling example
extension UIViewController {
static let shared : UIViewController = {
$0.initialize()
return $0
} (UIViewController())
func initialize() {
let swizzleClosure: () = {
UIViewController().swizzleViewDidLoad()
}()
swizzleClosure
}
// MARK: - Helpers
func swizzleViewDidLoad() {
let originalViewDidLoadSelector = #selector(UIViewController.viewDidLoad)
let swizzledViewDidLoadSelector = #selector(UIViewController.newViewDidLoad)
guard let originalViewDidLoadMethod = class_getInstanceMethod(UIViewController.self, originalViewDidLoadSelector),
let swizzledViewDidLoadMethod = class_getInstanceMethod(UIViewController.self, swizzledViewDidLoadSelector) else {
return
}
let didAddViewDidLoadMethod = class_addMethod(UIViewController.self, originalViewDidLoadSelector, method_getImplementation(swizzledViewDidLoadMethod), method_getTypeEncoding(swizzledViewDidLoadMethod))
if didAddViewDidLoadMethod {
class_replaceMethod(UIViewController.self, swizzledViewDidLoadSelector, method_getImplementation(originalViewDidLoadMethod), method_getTypeEncoding(swizzledViewDidLoadMethod))
} else {
method_exchangeImplementations(originalViewDidLoadMethod, swizzledViewDidLoadMethod)
}
}
// MARK: - Method Swizzling.
@objc func newViewDidLoad() {
// FIXME: add necessary things.
self.newViewDidLoad()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment